Blender  V2.59
readfile.c
Go to the documentation of this file.
00001 /*
00002  * $Id: readfile.c 39084 2011-08-05 20:45:26Z blendix $
00003  *
00004  * ***** BEGIN GPL LICENSE BLOCK *****
00005  *
00006  * This program is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU General Public License
00008  * as published by the Free Software Foundation; either version 2
00009  * of the License, or (at your option) any later version.
00010  *
00011  * This program is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014  * GNU General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU General Public License
00017  * along with this program; if not, write to the Free Software Foundation,
00018  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00019  *
00020  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
00021  * All rights reserved.
00022  *
00023  *
00024  * Contributor(s): Blender Foundation
00025  *
00026  * ***** END GPL LICENSE BLOCK *****
00027  *
00028  */
00029 
00035 #include "zlib.h"
00036 
00037 #include <limits.h>
00038 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
00039 #include <stdlib.h> // for getenv atoi
00040 #include <stddef.h> // for offsetof
00041 #include <fcntl.h> // for open
00042 #include <string.h> // for strrchr strncmp strstr
00043 #include <math.h> // for fabs
00044 
00045 #ifndef WIN32
00046         #include <unistd.h> // for read close
00047 #else
00048         #include <io.h> // for open close read
00049 #include "winsock2.h"
00050 #include "BLI_winstuff.h"
00051 #endif
00052 
00053 #include "DNA_anim_types.h"
00054 #include "DNA_armature_types.h"
00055 #include "DNA_actuator_types.h"
00056 #include "DNA_brush_types.h"
00057 #include "DNA_camera_types.h"
00058 #include "DNA_cloth_types.h"
00059 #include "DNA_controller_types.h"
00060 #include "DNA_constraint_types.h"
00061 #include "DNA_effect_types.h"
00062 #include "DNA_fileglobal_types.h"
00063 #include "DNA_genfile.h"
00064 #include "DNA_group_types.h"
00065 #include "DNA_gpencil_types.h"
00066 #include "DNA_ipo_types.h"
00067 #include "DNA_key_types.h"
00068 #include "DNA_lattice_types.h"
00069 #include "DNA_lamp_types.h"
00070 #include "DNA_meta_types.h"
00071 #include "DNA_material_types.h"
00072 #include "DNA_mesh_types.h"
00073 #include "DNA_meshdata_types.h"
00074 #include "DNA_nla_types.h"
00075 #include "DNA_node_types.h"
00076 #include "DNA_object_fluidsim.h" // NT
00077 #include "DNA_packedFile_types.h"
00078 #include "DNA_particle_types.h"
00079 #include "DNA_property_types.h"
00080 #include "DNA_text_types.h"
00081 #include "DNA_view3d_types.h"
00082 #include "DNA_screen_types.h"
00083 #include "DNA_sensor_types.h"
00084 #include "DNA_sdna_types.h"
00085 #include "DNA_scene_types.h"
00086 #include "DNA_sequence_types.h"
00087 #include "DNA_smoke_types.h"
00088 #include "DNA_sound_types.h"
00089 #include "DNA_space_types.h"
00090 #include "DNA_vfont_types.h"
00091 #include "DNA_world_types.h"
00092 
00093 #include "MEM_guardedalloc.h"
00094 
00095 #include "BLI_blenlib.h"
00096 #include "BLI_math.h"
00097 #include "BLI_utildefines.h"
00098 
00099 #include "BKE_anim.h"
00100 #include "BKE_action.h"
00101 #include "BKE_armature.h"
00102 #include "BKE_brush.h"
00103 #include "BKE_colortools.h"
00104 #include "BKE_constraint.h"
00105 #include "BKE_context.h"
00106 #include "BKE_curve.h"
00107 #include "BKE_deform.h"
00108 #include "BKE_effect.h" /* give_parteff */
00109 #include "BKE_fcurve.h"
00110 #include "BKE_global.h" // for G
00111 #include "BKE_group.h"
00112 #include "BKE_image.h"
00113 #include "BKE_lattice.h"
00114 #include "BKE_library.h" // for which_libbase
00115 #include "BKE_idcode.h"
00116 #include "BKE_material.h"
00117 #include "BKE_main.h" // for Main
00118 #include "BKE_mesh.h" // for ME_ defines (patching)
00119 #include "BKE_modifier.h"
00120 #include "BKE_multires.h"
00121 #include "BKE_node.h" // for tree type defines
00122 #include "BKE_object.h"
00123 #include "BKE_paint.h"
00124 #include "BKE_particle.h"
00125 #include "BKE_pointcache.h"
00126 #include "BKE_property.h" // for get_ob_property
00127 #include "BKE_report.h"
00128 #include "BKE_sca.h" // for init_actuator
00129 #include "BKE_scene.h"
00130 #include "BKE_screen.h"
00131 #include "BKE_sequencer.h"
00132 #include "BKE_texture.h" // for open_plugin_tex
00133 #include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
00134 #include "BKE_sound.h"
00135 
00136 //XXX #include "BIF_butspace.h" // badlevel, for do_versions, patching event codes
00137 //XXX #include "BIF_filelist.h" // badlevel too, where to move this? - elubie
00138 //XXX #include "BIF_previewrender.h" // bedlelvel, for struct RenderInfo
00139 #include "BLO_readfile.h"
00140 #include "BLO_undofile.h"
00141 
00142 #include "readfile.h"
00143 
00144 #include "PIL_time.h"
00145 
00146 #include <errno.h>
00147 
00148 /*
00149  Remark: still a weak point is the newaddress() function, that doesnt solve reading from
00150  multiple files at the same time
00151 
00152  (added remark: oh, i thought that was solved? will look at that... (ton)
00153 
00154 READ
00155 - Existing Library (Main) push or free
00156 - allocate new Main
00157 - load file
00158 - read SDNA
00159 - for each LibBlock
00160         - read LibBlock
00161         - if a Library
00162                 - make a new Main
00163                 - attach ID's to it
00164         - else
00165                 - read associated 'direct data'
00166                 - link direct data (internal and to LibBlock)
00167 - read FileGlobal
00168 - read USER data, only when indicated (file is ~/X.XX/startup.blend)
00169 - free file
00170 - per Library (per Main)
00171         - read file
00172         - read SDNA
00173         - find LibBlocks and attach IDs to Main
00174                 - if external LibBlock
00175                         - search all Main's
00176                                 - or it's already read,
00177                                 - or not read yet
00178                                 - or make new Main
00179         - per LibBlock
00180                 - read recursive
00181                 - read associated direct data
00182                 - link direct data (internal and to LibBlock)
00183         - free file
00184 - per Library with unread LibBlocks
00185         - read file
00186         - read SDNA
00187         - per LibBlock
00188                            - read recursive
00189                            - read associated direct data
00190                            - link direct data (internal and to LibBlock)
00191                 - free file
00192 - join all Mains
00193 - link all LibBlocks and indirect pointers to libblocks
00194 - initialize FileGlobal and copy pointers to Global
00195 */
00196 
00197 /* also occurs in library.c */
00198 /* GS reads the memory pointed at in a specific ordering. There are,
00199  * however two definitions for it. I have jotted them down here, both,
00200  * but I think the first one is actually used. The thing is that
00201  * big-endian systems might read this the wrong way round. OTOH, we
00202  * constructed the IDs that are read out with this macro explicitly as
00203  * well. I expect we'll sort it out soon... */
00204 
00205 /* from blendef: */
00206 #define GS(a)   (*((short *)(a)))
00207 
00208 /* from misc_util: flip the bytes from x  */
00209 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
00210 
00211 // only used here in readfile.c
00212 #define SWITCH_LONGINT(a) { \
00213         char s_i, *p_i; \
00214         p_i= (char *)&(a);  \
00215         s_i=p_i[0]; p_i[0]=p_i[7]; p_i[7]=s_i; \
00216         s_i=p_i[1]; p_i[1]=p_i[6]; p_i[6]=s_i; \
00217         s_i=p_i[2]; p_i[2]=p_i[5]; p_i[5]=s_i; \
00218         s_i=p_i[3]; p_i[3]=p_i[4]; p_i[4]=s_i; }
00219 
00220 /***/
00221 
00222 typedef struct OldNew {
00223         void *old, *newp;
00224         int nr;
00225 } OldNew;
00226 
00227 typedef struct OldNewMap {
00228         OldNew *entries;
00229         int nentries, entriessize;
00230         int sorted;
00231         int lasthit;
00232 } OldNewMap;
00233 
00234 
00235 /* local prototypes */
00236 static void *read_struct(FileData *fd, BHead *bh, const char *blockname);
00237 static void direct_link_modifiers(FileData *fd, ListBase *lb);
00238 
00239 static OldNewMap *oldnewmap_new(void) 
00240 {
00241         OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
00242         
00243         onm->entriessize= 1024;
00244         onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
00245         
00246         return onm;
00247 }
00248 
00249 static int verg_oldnewmap(const void *v1, const void *v2)
00250 {
00251         const struct OldNew *x1=v1, *x2=v2;
00252         
00253         if( x1->old > x2->old) return 1;
00254         else if( x1->old < x2->old) return -1;
00255         return 0;
00256 }
00257 
00258 
00259 static void oldnewmap_sort(FileData *fd) 
00260 {
00261         qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap);
00262         fd->libmap->sorted= 1;
00263 }
00264 
00265 /* nr is zero for data, and ID code for libdata */
00266 static void oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr) 
00267 {
00268         OldNew *entry;
00269 
00270         if(oldaddr==NULL || newaddr==NULL) return;
00271         
00272         if (onm->nentries==onm->entriessize) {
00273                 int osize= onm->entriessize;
00274                 OldNew *oentries= onm->entries;
00275 
00276                 onm->entriessize*= 2;
00277                 onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
00278 
00279                 memcpy(onm->entries, oentries, sizeof(*oentries)*osize);
00280                 MEM_freeN(oentries);
00281         }
00282 
00283         entry= &onm->entries[onm->nentries++];
00284         entry->old= oldaddr;
00285         entry->newp= newaddr;
00286         entry->nr= nr;
00287 }
00288 
00289 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, void *addr) 
00290 {
00291         int i;
00292 
00293         if(addr==NULL) return NULL;
00294 
00295         if (onm->lasthit<onm->nentries-1) {
00296                 OldNew *entry= &onm->entries[++onm->lasthit];
00297 
00298                 if (entry->old==addr) {
00299                         entry->nr++;
00300                         return entry->newp;
00301                 }
00302         }
00303 
00304         for (i=0; i<onm->nentries; i++) {
00305                 OldNew *entry= &onm->entries[i];
00306 
00307                 if (entry->old==addr) {
00308                         onm->lasthit= i;
00309 
00310                         entry->nr++;
00311                         return entry->newp;
00312                 }
00313         }
00314 
00315         return NULL;
00316 }
00317 
00318 /* for libdata, nr has ID code, no increment */
00319 static void *oldnewmap_liblookup(OldNewMap *onm, void *addr, void *lib) 
00320 {
00321         int i;
00322         
00323         if(addr==NULL) return NULL;
00324         
00325         /* lasthit works fine for non-libdata, linking there is done in same sequence as writing */
00326         if(onm->sorted) {
00327                 OldNew entry_s, *entry;
00328                 
00329                 entry_s.old= addr;
00330                 
00331                 entry= bsearch(&entry_s, onm->entries, onm->nentries, sizeof(OldNew), verg_oldnewmap);
00332                 if(entry) {
00333                         ID *id= entry->newp;
00334                         
00335                         if (id && (!lib || id->lib)) {
00336                                 return entry->newp;
00337                         }
00338                 }
00339         }
00340         
00341         for (i=0; i<onm->nentries; i++) {
00342                 OldNew *entry= &onm->entries[i];
00343 
00344                 if (entry->old==addr) {
00345                         ID *id= entry->newp;
00346 
00347                         if (id && (!lib || id->lib)) {
00348                                 return entry->newp;
00349                         }
00350                 }
00351         }
00352 
00353         return NULL;
00354 }
00355 
00356 static void oldnewmap_free_unused(OldNewMap *onm) 
00357 {
00358         int i;
00359 
00360         for (i=0; i<onm->nentries; i++) {
00361                 OldNew *entry= &onm->entries[i];
00362                 if (entry->nr==0) {
00363                         MEM_freeN(entry->newp);
00364                         entry->newp= NULL;
00365                 }
00366         }
00367 }
00368 
00369 static void oldnewmap_clear(OldNewMap *onm) 
00370 {
00371         onm->nentries= 0;
00372         onm->lasthit= 0;
00373 }
00374 
00375 static void oldnewmap_free(OldNewMap *onm) 
00376 {
00377         MEM_freeN(onm->entries);
00378         MEM_freeN(onm);
00379 }
00380 
00381 /***/
00382 
00383 static void read_libraries(FileData *basefd, ListBase *mainlist);
00384 
00385 /* ************ help functions ***************** */
00386 
00387 static void add_main_to_main(Main *mainvar, Main *from)
00388 {
00389         ListBase *lbarray[MAX_LIBARRAY], *fromarray[MAX_LIBARRAY];
00390         int a;
00391 
00392         set_listbasepointers(mainvar, lbarray);
00393         a= set_listbasepointers(from, fromarray);
00394         while(a--) {
00395                 BLI_movelisttolist(lbarray[a], fromarray[a]);
00396         }
00397 }
00398 
00399 void blo_join_main(ListBase *mainlist)
00400 {
00401         Main *tojoin, *mainl;
00402         
00403         
00404         mainl= mainlist->first;
00405         while ((tojoin= mainl->next)) {
00406                 add_main_to_main(mainl, tojoin);
00407                 BLI_remlink(mainlist, tojoin);
00408                 MEM_freeN(tojoin);
00409         }
00410 }
00411 
00412 static void split_libdata(ListBase *lb, Main *first)
00413 {
00414         ListBase *lbn;
00415         ID *id, *idnext;
00416         Main *mainvar;
00417 
00418         id= lb->first;
00419         while(id) {
00420                 idnext= id->next;
00421                 if(id->lib) {
00422                         mainvar= first;
00423                         while(mainvar) {
00424                                 if(mainvar->curlib==id->lib) {
00425                                         lbn= which_libbase(mainvar, GS(id->name));
00426                                         BLI_remlink(lb, id);
00427                                         BLI_addtail(lbn, id);
00428                                         break;
00429                                 }
00430                                 mainvar= mainvar->next;
00431                         }
00432                         if(mainvar==NULL) printf("error split_libdata\n");
00433                 }
00434                 id= idnext;
00435         }
00436 }
00437 
00438 void blo_split_main(ListBase *mainlist, Main *main)
00439 {
00440         ListBase *lbarray[MAX_LIBARRAY];
00441         Library *lib;
00442         int i;
00443 
00444         mainlist->first= mainlist->last= main;
00445         main->next= NULL;
00446 
00447         if(main->library.first==NULL)
00448                 return;
00449         
00450         for (lib= main->library.first; lib; lib= lib->id.next) {
00451                 Main *libmain= MEM_callocN(sizeof(Main), "libmain");
00452                 libmain->curlib= lib;
00453                 BLI_addtail(mainlist, libmain);
00454         }
00455 
00456         i= set_listbasepointers(main, lbarray);
00457         while(i--)
00458                 split_libdata(lbarray[i], main->next);
00459 }
00460 
00461 /* removes things like /blah/blah/../../blah/ etc, then writes in *name the full path */
00462 static void cleanup_path(const char *relabase, char *name)
00463 {
00464         char filename[FILE_MAXFILE];
00465         
00466         BLI_splitdirstring(name, filename);
00467         BLI_cleanup_dir(relabase, name);
00468         strcat(name, filename);
00469 }
00470 
00471 static void read_file_version(FileData *fd, Main *main)
00472 {
00473         BHead *bhead;
00474         
00475         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
00476                 if (bhead->code==GLOB) {
00477                         FileGlobal *fg= read_struct(fd, bhead, "Global");
00478                         if(fg) {
00479                                 main->subversionfile= fg->subversion;
00480                                 main->minversionfile= fg->minversion;
00481                                 main->minsubversionfile= fg->minsubversion;
00482                                 MEM_freeN(fg);
00483                         }
00484                         else if (bhead->code==ENDB)
00485                                 break;
00486                 }
00487         }
00488 }
00489 
00490 
00491 static Main *blo_find_main(FileData *fd, ListBase *mainlist, const char *filepath, const char *relabase)
00492 {
00493         Main *m;
00494         Library *lib;
00495         char name1[FILE_MAXDIR+FILE_MAXFILE];
00496         
00497         BLI_strncpy(name1, filepath, sizeof(name1));
00498         cleanup_path(relabase, name1);
00499 //      printf("blo_find_main: original in  %s\n", name);
00500 //      printf("blo_find_main: converted to %s\n", name1);
00501 
00502         for (m= mainlist->first; m; m= m->next) {
00503                 char *libname= (m->curlib)?m->curlib->filepath:m->name;
00504                 
00505                 if (BLI_path_cmp(name1, libname) == 0) {
00506                         if(G.f & G_DEBUG) printf("blo_find_main: found library %s\n", libname);
00507                         return m;
00508                 }
00509         }
00510 
00511         m= MEM_callocN(sizeof(Main), "find_main");
00512         BLI_addtail(mainlist, m);
00513 
00514         lib= alloc_libblock(&m->library, ID_LI, "lib");
00515         strncpy(lib->name, filepath, sizeof(lib->name)-1);
00516         BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath));
00517         
00518         m->curlib= lib;
00519         
00520         read_file_version(fd, m);
00521         
00522         if(G.f & G_DEBUG) printf("blo_find_main: added new lib %s\n", filepath);
00523         return m;
00524 }
00525 
00526 
00527 /* ************ FILE PARSING ****************** */
00528 
00529 static void switch_endian_bh4(BHead4 *bhead)
00530 {
00531         /* the ID_.. codes */
00532         if((bhead->code & 0xFFFF)==0) bhead->code >>=16;
00533 
00534         if (bhead->code != ENDB) {
00535                 SWITCH_INT(bhead->len);
00536                 SWITCH_INT(bhead->SDNAnr);
00537                 SWITCH_INT(bhead->nr);
00538         }
00539 }
00540 
00541 static void switch_endian_bh8(BHead8 *bhead)
00542 {
00543         /* the ID_.. codes */
00544         if((bhead->code & 0xFFFF)==0) bhead->code >>=16;
00545 
00546         if (bhead->code != ENDB) {
00547                 SWITCH_INT(bhead->len);
00548                 SWITCH_INT(bhead->SDNAnr);
00549                 SWITCH_INT(bhead->nr);
00550         }
00551 }
00552 
00553 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
00554 {
00555         BHead4 *bhead4 = (BHead4 *) bhead;
00556 #if defined(WIN32) && !defined(FREE_WINDOWS)
00557         __int64 old;
00558 #else
00559         long long old;
00560 #endif
00561 
00562         bhead4->code= bhead8->code;
00563         bhead4->len= bhead8->len;
00564 
00565         if (bhead4->code != ENDB) {
00566 
00567                 //perform a endian swap on 64bit pointers, otherwise the pointer might map to zero
00568                 //0x0000000000000000000012345678 would become 0x12345678000000000000000000000000
00569                 if (do_endian_swap) {
00570                         SWITCH_LONGINT(bhead8->old);
00571                 }
00572 
00573                 /* this patch is to avoid a long long being read from not-eight aligned positions
00574                    is necessary on any modern 64bit architecture) */
00575                 memcpy(&old, &bhead8->old, 8);
00576                 bhead4->old = (int) (old >> 3);
00577 
00578                 bhead4->SDNAnr= bhead8->SDNAnr;
00579                 bhead4->nr= bhead8->nr;
00580         }
00581 }
00582 
00583 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
00584 {
00585         BHead8 *bhead8 = (BHead8 *) bhead;
00586 
00587         bhead8->code= bhead4->code;
00588         bhead8->len= bhead4->len;
00589 
00590         if (bhead8->code != ENDB) {
00591                 bhead8->old= bhead4->old;
00592                 bhead8->SDNAnr= bhead4->SDNAnr;
00593                 bhead8->nr= bhead4->nr;
00594         }
00595 }
00596 
00597 static BHeadN *get_bhead(FileData *fd)
00598 {
00599         BHeadN *new_bhead = NULL;
00600         int readsize;
00601         
00602         if (fd) {
00603                 if ( ! fd->eof) {
00604                         /* initializing to zero isn't strictly needed but shuts valgrind up
00605                          * since uninitialized memory gets compared */
00606                         BHead8 bhead8= {0};
00607                         BHead4 bhead4= {0};
00608                         BHead  bhead= {0};
00609                         
00610                         // First read the bhead structure.
00611                         // Depending on the platform the file was written on this can
00612                         // be a big or little endian BHead4 or BHead8 structure.
00613 
00614                         // As usual 'ENDB' (the last *partial* bhead of the file)
00615                         // needs some special handling. We don't want to EOF just yet.
00616 
00617                         if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
00618                                 bhead4.code = DATA;
00619                                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
00620 
00621                                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
00622                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
00623                                                 switch_endian_bh4(&bhead4);
00624                                         }
00625 
00626                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
00627                                                 bh8_from_bh4(&bhead, &bhead4);
00628                                         } else {
00629                                                 memcpy(&bhead, &bhead4, sizeof(bhead));
00630                                         }
00631                                 } else {
00632                                         fd->eof = 1;
00633                                         bhead.len= 0;
00634                                 }
00635                         } else {
00636                                 bhead8.code = DATA;
00637                                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
00638 
00639                                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
00640                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
00641                                                 switch_endian_bh8(&bhead8);
00642                                         }
00643 
00644                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
00645                                                 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
00646                                         } else {
00647                                                 memcpy(&bhead, &bhead8, sizeof(bhead));
00648                                         }
00649                                 } else {
00650                                         fd->eof = 1;
00651                                         bhead.len= 0;
00652                                 }
00653                         }
00654 
00655                         /* make sure people are not trying to pass bad blend files */
00656                         if (bhead.len < 0) fd->eof = 1;
00657 
00658                         // bhead now contains the (converted) bhead structure. Now read
00659                         // the associated data and put everything in a BHeadN (creative naming !)
00660 
00661                         if ( ! fd->eof) {
00662                                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
00663                                 if (new_bhead) {
00664                                         new_bhead->next = new_bhead->prev = NULL;
00665                                         new_bhead->bhead = bhead;
00666 
00667                                         readsize = fd->read(fd, new_bhead + 1, bhead.len);
00668 
00669                                         if (readsize != bhead.len) {
00670                                                 fd->eof = 1;
00671                                                 MEM_freeN(new_bhead);
00672                                                 new_bhead = NULL;
00673                                         }
00674                                 } else {
00675                                         fd->eof = 1;
00676                                 }
00677                         }
00678                 }
00679         }
00680 
00681         // We've read a new block. Now add it to the list
00682         // of blocks.
00683 
00684         if (new_bhead) {
00685                 BLI_addtail(&fd->listbase, new_bhead);
00686         }
00687 
00688         return(new_bhead);
00689 }
00690 
00691 BHead *blo_firstbhead(FileData *fd)
00692 {
00693         BHeadN *new_bhead;
00694         BHead *bhead = NULL;
00695 
00696         // Rewind the file
00697         // Read in a new block if necessary
00698 
00699         new_bhead = fd->listbase.first;
00700         if (new_bhead == NULL) {
00701                 new_bhead = get_bhead(fd);
00702         }
00703 
00704         if (new_bhead) {
00705                 bhead = &new_bhead->bhead;
00706         }
00707 
00708         return(bhead);
00709 }
00710 
00711 BHead *blo_prevbhead(FileData *UNUSED(fd), BHead *thisblock)
00712 {
00713         BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
00714         BHeadN *prev= bheadn->prev;
00715 
00716         return prev?&prev->bhead:NULL;
00717 }
00718 
00719 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
00720 {
00721         BHeadN *new_bhead = NULL;
00722         BHead *bhead = NULL;
00723 
00724         if (thisblock) {
00725                 // bhead is actually a sub part of BHeadN
00726                 // We calculate the BHeadN pointer from the BHead pointer below
00727                 new_bhead = (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
00728 
00729                 // get the next BHeadN. If it doesn't exist we read in the next one
00730                 new_bhead = new_bhead->next;
00731                 if (new_bhead == NULL) {
00732                         new_bhead = get_bhead(fd);
00733                 }
00734         }
00735 
00736         if (new_bhead) {
00737                 // here we do the reverse:
00738                 // go from the BHeadN pointer to the BHead pointer
00739                 bhead = &new_bhead->bhead;
00740         }
00741 
00742         return(bhead);
00743 }
00744 
00745 static void decode_blender_header(FileData *fd)
00746 {
00747         char header[SIZEOFBLENDERHEADER], num[4];
00748         int readsize;
00749 
00750         // read in the header data
00751         readsize = fd->read(fd, header, sizeof(header));
00752 
00753         if (readsize == sizeof(header)) {
00754                 if(strncmp(header, "BLENDER", 7) == 0) {
00755                         int remove_this_endian_test= 1;
00756 
00757                         fd->flags |= FD_FLAGS_FILE_OK;
00758 
00759                         // what size are pointers in the file ?
00760                         if(header[7]=='_') {
00761                                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
00762                                 if (sizeof(void *) != 4) {
00763                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
00764                                 }
00765                         } else {
00766                                 if (sizeof(void *) != 8) {
00767                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
00768                                 }
00769                         }
00770 
00771                         // is the file saved in a different endian
00772                         // than we need ?
00773                         if (((((char*)&remove_this_endian_test)[0]==1)?L_ENDIAN:B_ENDIAN) != ((header[8]=='v')?L_ENDIAN:B_ENDIAN)) {
00774                                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
00775                         }
00776 
00777                         // get the version number
00778 
00779                         memcpy(num, header+9, 3);
00780                         num[3] = 0;
00781                         fd->fileversion = atoi(num);
00782                 }
00783         }
00784 }
00785 
00786 static int read_file_dna(FileData *fd)
00787 {
00788         BHead *bhead;
00789 
00790         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
00791                 if (bhead->code==DNA1) {
00792                         int do_endian_swap= (fd->flags&FD_FLAGS_SWITCH_ENDIAN)?1:0;
00793 
00794                         fd->filesdna= DNA_sdna_from_data(&bhead[1], bhead->len, do_endian_swap);
00795                         if (fd->filesdna) {
00796                                 
00797                                 fd->compflags= DNA_struct_get_compareflags(fd->filesdna, fd->memsdna);
00798                                 /* used to retrieve ID names from (bhead+1) */
00799                                 fd->id_name_offs= DNA_elem_offset(fd->filesdna, "ID", "char", "name[]");
00800                         }
00801 
00802                         return 1;
00803                 } else if (bhead->code==ENDB)
00804                         break;
00805         }
00806 
00807         return 0;
00808 }
00809 
00810 static int fd_read_from_file(FileData *filedata, void *buffer, unsigned int size)
00811 {
00812         int readsize = read(filedata->filedes, buffer, size);
00813 
00814         if (readsize < 0) {
00815                 readsize = EOF;
00816         } else {
00817                 filedata->seek += readsize;
00818         }
00819 
00820         return (readsize);
00821 }
00822 
00823 static int fd_read_gzip_from_file(FileData *filedata, void *buffer, unsigned int size)
00824 {
00825         int readsize = gzread(filedata->gzfiledes, buffer, size);
00826 
00827         if (readsize < 0) {
00828                 readsize = EOF;
00829         } else {
00830                 filedata->seek += readsize;
00831         }
00832 
00833         return (readsize);
00834 }
00835 
00836 static int fd_read_from_memory(FileData *filedata, void *buffer, unsigned int size)
00837 {
00838         // don't read more bytes then there are available in the buffer
00839         int readsize = (int)MIN2(size, (unsigned int)(filedata->buffersize - filedata->seek));
00840 
00841         memcpy(buffer, filedata->buffer + filedata->seek, readsize);
00842         filedata->seek += readsize;
00843 
00844         return (readsize);
00845 }
00846 
00847 static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int size)
00848 {
00849         static unsigned int seek= 1<<30;        /* the current position */
00850         static unsigned int offset= 0;          /* size of previous chunks */
00851         static MemFileChunk *chunk=NULL;
00852         unsigned int chunkoffset, readsize, totread;
00853         
00854         if(size==0) return 0;
00855         
00856         if(seek != (unsigned int)filedata->seek) {
00857                 chunk= filedata->memfile->chunks.first;
00858                 seek= 0;
00859                 
00860                 while(chunk) {
00861                         if(seek + chunk->size > (unsigned) filedata->seek) break;
00862                         seek+= chunk->size;
00863                         chunk= chunk->next;
00864                 }
00865                 offset= seek;
00866                 seek= filedata->seek;
00867         }
00868         
00869         if(chunk) {
00870                 totread= 0;
00871 
00872                 do {
00873                         /* first check if it's on the end if current chunk */
00874                         if(seek-offset == chunk->size) {
00875                                 offset+= chunk->size;
00876                                 chunk= chunk->next;
00877                         }
00878 
00879                         /* debug, should never happen */
00880                         if(chunk==NULL) {
00881                                 printf("illegal read, chunk zero\n");
00882                                 return 0;
00883                         }
00884 
00885                         chunkoffset= seek-offset;
00886                         readsize= size-totread;
00887 
00888                         /* data can be spread over multiple chunks, so clamp size
00889                          * to within this chunk, and then it will read further in
00890                          * the next chunk */
00891                         if(chunkoffset+readsize > chunk->size)
00892                                 readsize= chunk->size-chunkoffset;
00893 
00894                         memcpy((char*)buffer+totread, chunk->buf+chunkoffset, readsize);
00895                         totread += readsize;
00896                         filedata->seek += readsize;
00897                         seek += readsize;
00898                 } while(totread < size);
00899                 
00900                 return totread;
00901         }
00902 
00903         return 0;
00904 }
00905 
00906 static FileData *filedata_new(void)
00907 {
00908         FileData *fd = MEM_callocN(sizeof(FileData), "FileData");
00909 
00910         fd->filedes = -1;
00911         fd->gzfiledes = NULL;
00912 
00913                 /* XXX, this doesn't need to be done all the time,
00914                  * but it keeps us reentrant,  remove once we have
00915                  * a lib that provides a nice lock. - zr
00916                  */
00917         fd->memsdna = DNA_sdna_from_data(DNAstr,  DNAlen,  0);
00918 
00919         fd->datamap = oldnewmap_new();
00920         fd->globmap = oldnewmap_new();
00921         fd->libmap = oldnewmap_new();
00922 
00923         return fd;
00924 }
00925 
00926 static FileData *blo_decode_and_check(FileData *fd, ReportList *reports)
00927 {
00928         decode_blender_header(fd);
00929 
00930         if (fd->flags & FD_FLAGS_FILE_OK) {
00931                 if (!read_file_dna(fd)) {
00932                         BKE_reportf(reports, RPT_ERROR, "Failed to read blend file: \"%s\", incomplete", fd->relabase);
00933                         blo_freefiledata(fd);
00934                         fd= NULL;
00935                 }
00936         } 
00937         else {
00938                 BKE_reportf(reports, RPT_ERROR, "Failed to read blend file: \"%s\", not a blend file", fd->relabase);
00939                 blo_freefiledata(fd);
00940                 fd= NULL;
00941         }
00942 
00943         return fd;
00944 }
00945 
00946 /* cannot be called with relative paths anymore! */
00947 /* on each new library added, it now checks for the current FileData and expands relativeness */
00948 FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
00949 {
00950         gzFile gzfile;
00951         errno= 0;
00952         gzfile= gzopen(filepath, "rb");
00953 
00954         if (gzfile == (gzFile)Z_NULL) {
00955                 BKE_reportf(reports, RPT_ERROR, "Unable to open \"%s\": %s.", filepath, errno ? strerror(errno) : "Unknown error reading file");
00956                 return NULL;
00957         } else {
00958                 FileData *fd = filedata_new();
00959                 fd->gzfiledes = gzfile;
00960                 fd->read = fd_read_gzip_from_file;
00961 
00962                 /* needed for library_append and read_libraries */
00963                 BLI_strncpy(fd->relabase, filepath, sizeof(fd->relabase));
00964 
00965                 return blo_decode_and_check(fd, reports);
00966         }
00967 }
00968 
00969 FileData *blo_openblendermemory(void *mem, int memsize, ReportList *reports)
00970 {
00971         if (!mem || memsize<SIZEOFBLENDERHEADER) {
00972                 BKE_report(reports, RPT_ERROR, (mem)? "Unable to read": "Unable to open");
00973                 return NULL;
00974         } else {
00975                 FileData *fd= filedata_new();
00976                 fd->buffer= mem;
00977                 fd->buffersize= memsize;
00978                 fd->read= fd_read_from_memory;
00979                 fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
00980 
00981                 return blo_decode_and_check(fd, reports);
00982         }
00983 }
00984 
00985 FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports)
00986 {
00987         if (!memfile) {
00988                 BKE_report(reports, RPT_ERROR, "Unable to open blend <memory>");
00989                 return NULL;
00990         } else {
00991                 FileData *fd= filedata_new();
00992                 fd->memfile= memfile;
00993 
00994                 fd->read= fd_read_from_memfile;
00995                 fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
00996 
00997                 return blo_decode_and_check(fd, reports);
00998         }
00999 }
01000 
01001 
01002 void blo_freefiledata(FileData *fd)
01003 {
01004         if (fd) {
01005                 
01006                 if (fd->filedes != -1) {
01007                         close(fd->filedes);
01008                 }
01009 
01010                 if (fd->gzfiledes != NULL)
01011                 {
01012                         gzclose(fd->gzfiledes);
01013                 }
01014 
01015                 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
01016                         MEM_freeN(fd->buffer);
01017                         fd->buffer = NULL;
01018                 }
01019 
01020                 // Free all BHeadN data blocks
01021                 BLI_freelistN(&fd->listbase);
01022 
01023                 if (fd->memsdna)
01024                         DNA_sdna_free(fd->memsdna);
01025                 if (fd->filesdna)
01026                         DNA_sdna_free(fd->filesdna);
01027                 if (fd->compflags)
01028                         MEM_freeN(fd->compflags);
01029 
01030                 if (fd->datamap)
01031                         oldnewmap_free(fd->datamap);
01032                 if (fd->globmap)
01033                         oldnewmap_free(fd->globmap);
01034                 if (fd->imamap)
01035                         oldnewmap_free(fd->imamap);
01036                 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
01037                         oldnewmap_free(fd->libmap);
01038                 if (fd->bheadmap)
01039                         MEM_freeN(fd->bheadmap);
01040                 
01041                 MEM_freeN(fd);
01042         }
01043 }
01044 
01045 /* ************ DIV ****************** */
01046 
01047 int BLO_has_bfile_extension(char *str)
01048 {
01049         return (BLI_testextensie(str, ".ble") || BLI_testextensie(str, ".blend") || BLI_testextensie(str, ".blend.gz"));
01050 }
01051 
01052 int BLO_is_a_library(const char *path, char *dir, char *group)
01053 {
01054         /* return ok when a blenderfile, in dir is the filename,
01055          * in group the type of libdata
01056          */
01057         int len;
01058         char *fd;
01059         
01060         strcpy(dir, path);
01061         len= strlen(dir);
01062         if(len<7) return 0;
01063         if( dir[len-1] != '/' && dir[len-1] != '\\') return 0;
01064         
01065         group[0]= 0;
01066         dir[len-1]= 0;
01067 
01068         /* Find the last slash */
01069         fd= BLI_last_slash(dir);
01070 
01071         if(fd==NULL) return 0;
01072         *fd= 0;
01073         if(BLO_has_bfile_extension(fd+1)) {
01074                 /* the last part of the dir is a .blend file, no group follows */
01075                 *fd= '/'; /* put back the removed slash separating the dir and the .blend file name */
01076         }
01077         else {          
01078                 char *gp = fd+1; // in case we have a .blend file, gp points to the group
01079 
01080                 /* Find the last slash */
01081                 fd= BLI_last_slash(dir);
01082                 if (!fd || !BLO_has_bfile_extension(fd+1)) return 0;
01083 
01084                 /* now we know that we are in a blend file and it is safe to 
01085                    assume that gp actually points to a group */
01086                 if (strcmp("Screen", gp)!=0)
01087                         BLI_strncpy(group, gp, GROUP_MAX);
01088         }
01089         return 1;
01090 }
01091 
01092 /* ************** OLD POINTERS ******************* */
01093 
01094 static void *newdataadr(FileData *fd, void *adr)                /* only direct databocks */
01095 {
01096         return oldnewmap_lookup_and_inc(fd->datamap, adr);
01097 }
01098 
01099 static void *newglobadr(FileData *fd, void *adr)                /* direct datablocks with global linking */
01100 {
01101         return oldnewmap_lookup_and_inc(fd->globmap, adr);
01102 }
01103 
01104 static void *newimaadr(FileData *fd, void *adr)         /* used to restore image data after undo */
01105 {
01106         if(fd->imamap && adr)
01107                 return oldnewmap_lookup_and_inc(fd->imamap, adr);
01108         return NULL;
01109 }
01110 
01111 
01112 static void *newlibadr(FileData *fd, void *lib, void *adr)              /* only lib data */
01113 {
01114         return oldnewmap_liblookup(fd->libmap, adr, lib);
01115 }
01116 
01117 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
01118 {
01119         ID *id= newlibadr(fd, lib, adr);
01120 
01121         if(id)
01122                 id->us++;
01123 
01124         return id;
01125 }
01126 
01127 static void change_idid_adr_fd(FileData *fd, void *old, void *new)
01128 {
01129         int i;
01130         
01131         for (i=0; i<fd->libmap->nentries; i++) {
01132                 OldNew *entry= &fd->libmap->entries[i];
01133                 
01134                 if (old==entry->newp && entry->nr==ID_ID) {
01135                         entry->newp= new;
01136                         if(new) entry->nr= GS( ((ID *)new)->name );
01137                         break;
01138                 }
01139         }
01140 }
01141 
01142 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
01143 {
01144         Main *mainptr;
01145         
01146         for(mainptr= mainlist->first; mainptr; mainptr= mainptr->next) {
01147                 FileData *fd;
01148                 
01149                 if(mainptr->curlib) fd= mainptr->curlib->filedata;
01150                 else fd= basefd;
01151                 
01152                 if(fd) {
01153                         change_idid_adr_fd(fd, old, new);
01154                 }
01155         }
01156 }
01157 
01158 /* lib linked proxy objects point to our local data, we need
01159  * to clear that pointer before reading the undo memfile since
01160  * the object might be removed, it is set again in reading
01161  * if the local object still exists */
01162 void blo_clear_proxy_pointers_from_lib(Main *oldmain)
01163 {
01164         Object *ob= oldmain->object.first;
01165         
01166         for(;ob; ob= ob->id.next)
01167                 if(ob->id.lib)
01168                         ob->proxy_from= NULL;
01169 }
01170 
01171 void blo_make_image_pointer_map(FileData *fd, Main *oldmain)
01172 {
01173         Image *ima= oldmain->image.first;
01174         Scene *sce= oldmain->scene.first;
01175         int a;
01176         
01177         fd->imamap= oldnewmap_new();
01178         
01179         for(;ima; ima= ima->id.next) {
01180                 Link *ibuf= ima->ibufs.first;
01181                 for(; ibuf; ibuf= ibuf->next) 
01182                         oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
01183                 if(ima->gputexture)
01184                         oldnewmap_insert(fd->imamap, ima->gputexture, ima->gputexture, 0);
01185                 for(a=0; a<IMA_MAX_RENDER_SLOT; a++)
01186                         if(ima->renders[a])
01187                                 oldnewmap_insert(fd->imamap, ima->renders[a], ima->renders[a], 0);
01188         }
01189         for(; sce; sce= sce->id.next) {
01190                 if(sce->nodetree) {
01191                         bNode *node;
01192                         for(node= sce->nodetree->nodes.first; node; node= node->next)
01193                                 oldnewmap_insert(fd->imamap, node->preview, node->preview, 0);
01194                 }
01195         }
01196 }
01197 
01198 /* set old main image ibufs to zero if it has been restored */
01199 /* this works because freeing old main only happens after this call */
01200 void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
01201 {
01202         OldNew *entry= fd->imamap->entries;
01203         Image *ima= oldmain->image.first;
01204         Scene *sce= oldmain->scene.first;
01205         int i;
01206         
01207         /* used entries were restored, so we put them to zero */
01208         for (i=0; i<fd->imamap->nentries; i++, entry++) {
01209                 if (entry->nr>0)
01210                         entry->newp= NULL;
01211         }
01212         
01213         for(;ima; ima= ima->id.next) {
01214                 Link *ibuf, *next;
01215                 
01216                 /* this mirrors direct_link_image */
01217                 for(ibuf= ima->ibufs.first; ibuf; ibuf= next) {
01218                         next= ibuf->next;
01219                         if(NULL==newimaadr(fd, ibuf)) { /* so was restored */
01220                                 BLI_remlink(&ima->ibufs, ibuf);
01221                                 ima->bindcode= 0;
01222                                 ima->gputexture= NULL;
01223                         }
01224                 }
01225                 for(i=0; i<IMA_MAX_RENDER_SLOT; i++)
01226                         ima->renders[i]= newimaadr(fd, ima->renders[i]);
01227 
01228                 ima->gputexture= newimaadr(fd, ima->gputexture);
01229         }
01230         for(; sce; sce= sce->id.next) {
01231                 if(sce->nodetree) {
01232                         bNode *node;
01233                         for(node= sce->nodetree->nodes.first; node; node= node->next)
01234                                 node->preview= newimaadr(fd, node->preview);
01235                 }
01236         }
01237 }
01238 
01239 /* undo file support: add all library pointers in lookup */
01240 void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd)
01241 {
01242         Main *ptr= mainlist->first;
01243         ListBase *lbarray[MAX_LIBARRAY];
01244         
01245         for(ptr= ptr->next; ptr; ptr= ptr->next) {
01246                 int i= set_listbasepointers(ptr, lbarray);
01247                 while(i--) {
01248                         ID *id;
01249                         for(id= lbarray[i]->first; id; id= id->next)
01250                                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
01251                 }
01252         }
01253 }
01254                 
01255 
01256 /* ********** END OLD POINTERS ****************** */
01257 /* ********** READ FILE ****************** */
01258 
01259 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
01260 {
01261         int blocksize, nblocks;
01262         char *data;
01263 
01264         data= (char *)(bhead+1);
01265         blocksize= filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
01266 
01267         nblocks= bhead->nr;
01268         while(nblocks--) {
01269                 DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data);
01270 
01271                 data+= blocksize;
01272         }
01273 }
01274 
01275 static void *read_struct(FileData *fd, BHead *bh, const char *blockname)
01276 {
01277         void *temp= NULL;
01278 
01279         if (bh->len) {
01280                 /* switch is based on file dna */
01281                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
01282                         switch_endian_structs(fd->filesdna, bh);
01283 
01284                 if (fd->compflags[bh->SDNAnr]) {        /* flag==0: doesn't exist anymore */
01285                         if(fd->compflags[bh->SDNAnr]==2) {
01286                                 temp= DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
01287                         } else {
01288                                 temp= MEM_mallocN(bh->len, blockname);
01289                                 memcpy(temp, (bh+1), bh->len);
01290                         }
01291                 }
01292         }
01293 
01294         return temp;
01295 }
01296 
01297 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
01298 {
01299         Link *ln, *prev;
01300 
01301         if(lb->first==NULL) return;
01302 
01303         lb->first= newdataadr(fd, lb->first);
01304         ln= lb->first;
01305         prev= NULL;
01306         while(ln) {
01307                 ln->next= newdataadr(fd, ln->next);
01308                 ln->prev= prev;
01309                 prev= ln;
01310                 ln= ln->next;
01311         }
01312         lb->last= prev;
01313 }
01314 
01315 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
01316 {
01317         Link *ln, *prev;
01318         void *poin;
01319 
01320         if(lb->first==NULL) return;
01321         poin= newdataadr(fd, lb->first);
01322         if(lb->first) {
01323                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
01324         }
01325         lb->first= poin;
01326 
01327         ln= lb->first;
01328         prev= NULL;
01329         while(ln) {
01330                 poin= newdataadr(fd, ln->next);
01331                 if(ln->next) {
01332                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
01333                 }
01334                 ln->next= poin;
01335                 ln->prev= prev;
01336                 prev= ln;
01337                 ln= ln->next;
01338         }
01339         lb->last= prev;
01340 }
01341 
01342 static void test_pointer_array(FileData *fd, void **mat)
01343 {
01344 #if defined(WIN32) && !defined(FREE_WINDOWS)
01345         __int64 *lpoin, *lmat;
01346 #else
01347         long long *lpoin, *lmat;
01348 #endif
01349         int *ipoin, *imat;
01350         size_t len;
01351 
01352                 /* manually convert the pointer array in
01353                  * the old dna format to a pointer array in
01354                  * the new dna format.
01355                  */
01356         if(*mat) {
01357                 len= MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
01358 
01359                 if(fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
01360                         ipoin=imat= MEM_mallocN( len*4, "newmatar");
01361                         lpoin= *mat;
01362 
01363                         while(len-- > 0) {
01364                                 if((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
01365                                         SWITCH_LONGINT(*lpoin);
01366                                 *ipoin= (int) ((*lpoin) >> 3);
01367                                 ipoin++;
01368                                 lpoin++;
01369                         }
01370                         MEM_freeN(*mat);
01371                         *mat= imat;
01372                 }
01373 
01374                 if(fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
01375                         lpoin=lmat= MEM_mallocN( len*8, "newmatar");
01376                         ipoin= *mat;
01377 
01378                         while(len-- > 0) {
01379                                 *lpoin= *ipoin;
01380                                 ipoin++;
01381                                 lpoin++;
01382                         }
01383                         MEM_freeN(*mat);
01384                         *mat= lmat;
01385                 }
01386         }
01387 }
01388 
01389 /* ************ READ ID Properties *************** */
01390 
01391 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
01392 static void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
01393 
01394 static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
01395 {
01396         IDProperty *array;
01397         int i;
01398 
01399         /*since we didn't save the extra buffer, set totallen to len.*/
01400         prop->totallen = prop->len;
01401         prop->data.pointer = newdataadr(fd, prop->data.pointer);
01402 
01403         array= (IDProperty*) prop->data.pointer;
01404         
01405         /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared
01406          * theres not really anything we can do to correct this, at least dont crash */
01407         if(array==NULL) {
01408                 prop->len= 0;
01409                 prop->totallen= 0;
01410         }
01411         
01412 
01413         for(i=0; i<prop->len; i++)
01414                 IDP_DirectLinkProperty(&array[i], switch_endian, fd);
01415 }
01416 
01417 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
01418 {
01419         IDProperty **array;
01420         int i;
01421 
01422         /*since we didn't save the extra buffer, set totallen to len.*/
01423         prop->totallen = prop->len;
01424         prop->data.pointer = newdataadr(fd, prop->data.pointer);
01425 
01426         if(prop->subtype == IDP_GROUP) {
01427                 test_pointer_array(fd, prop->data.pointer);
01428                 array= prop->data.pointer;
01429 
01430                 for(i=0; i<prop->len; i++)
01431                         IDP_DirectLinkProperty(array[i], switch_endian, fd);
01432         }
01433         else if(prop->subtype == IDP_DOUBLE) {
01434                 if (switch_endian) {
01435                         for (i=0; i<prop->len; i++) {
01436                                 SWITCH_LONGINT(((double*)prop->data.pointer)[i]);
01437                         }
01438                 }
01439         }
01440         else {
01441                 if (switch_endian) {
01442                         for (i=0; i<prop->len; i++) {
01443                                 SWITCH_INT(((int*)prop->data.pointer)[i]);
01444                         }
01445                 }
01446         }
01447 }
01448 
01449 static void IDP_DirectLinkString(IDProperty *prop, FileData *fd)
01450 {
01451         /*since we didn't save the extra string buffer, set totallen to len.*/
01452         prop->totallen = prop->len;
01453         prop->data.pointer = newdataadr(fd, prop->data.pointer);
01454 }
01455 
01456 static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *fd)
01457 {
01458         ListBase *lb = &prop->data.group;
01459         IDProperty *loop;
01460 
01461         link_list(fd, lb);
01462 
01463         /*Link child id properties now*/
01464         for (loop=prop->data.group.first; loop; loop=loop->next) {
01465                 IDP_DirectLinkProperty(loop, switch_endian, fd);
01466         }
01467 }
01468 
01469 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
01470 {
01471         switch (prop->type) {
01472                 case IDP_GROUP:
01473                         IDP_DirectLinkGroup(prop, switch_endian, fd);
01474                         break;
01475                 case IDP_STRING:
01476                         IDP_DirectLinkString(prop, fd);
01477                         break;
01478                 case IDP_ARRAY:
01479                         IDP_DirectLinkArray(prop, switch_endian, fd);
01480                         break;
01481                 case IDP_IDPARRAY:
01482                         IDP_DirectLinkIDPArray(prop, switch_endian, fd);
01483                         break;
01484                 case IDP_DOUBLE:
01485                         /*erg, stupid doubles.  since I'm storing them
01486                          in the same field as int val; val2 in the
01487                          IDPropertyData struct, they have to deal with
01488                          endianness specifically
01489                          
01490                          in theory, val and val2 would've already been swapped
01491                          if switch_endian is true, so we have to first unswap
01492                          them then reswap them as a single 64-bit entity.
01493                          */
01494                         
01495                         if (switch_endian) {
01496                                 SWITCH_INT(prop->data.val);
01497                                 SWITCH_INT(prop->data.val2);
01498                                 SWITCH_LONGINT(prop->data.val);
01499                         }
01500                         
01501                         break;
01502         }
01503 }
01504 
01505 /*stub function*/
01506 static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endian), FileData *UNUSED(fd))
01507 {
01508 }
01509 
01510 /* ************ READ CurveMapping *************** */
01511 
01512 /* cuma itself has been read! */
01513 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
01514 {
01515         int a;
01516         
01517         /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
01518         cumap->flag &= ~CUMA_PREMULLED;
01519         
01520         for(a=0; a<CM_TOT; a++) {
01521                 cumap->cm[a].curve= newdataadr(fd, cumap->cm[a].curve);
01522                 cumap->cm[a].table= NULL;
01523                 cumap->cm[a].premultable= NULL;
01524         }
01525 }
01526 
01527 /* ************ READ Brush *************** */
01528 /* library brush linking after fileread */
01529 static void lib_link_brush(FileData *fd, Main *main)
01530 {
01531         Brush *brush;
01532         
01533         /* only link ID pointers */
01534         for(brush= main->brush.first; brush; brush= brush->id.next) {
01535                 if(brush->id.flag & LIB_NEEDLINK) {
01536                         brush->id.flag -= LIB_NEEDLINK;
01537 
01538                         brush->mtex.tex= newlibadr_us(fd, brush->id.lib, brush->mtex.tex);
01539                         brush->clone.image= newlibadr_us(fd, brush->id.lib, brush->clone.image);
01540                 }
01541         }
01542 }
01543 
01544 static void direct_link_brush(FileData *fd, Brush *brush)
01545 {
01546         /* brush itself has been read */
01547 
01548         /* fallof curve */
01549         brush->curve= newdataadr(fd, brush->curve);
01550         if(brush->curve)
01551                 direct_link_curvemapping(fd, brush->curve);
01552         else
01553                 brush_curve_preset(brush, CURVE_PRESET_SHARP);
01554 
01555         brush->preview= NULL;
01556         brush->icon_imbuf= NULL;
01557 }
01558 
01559 static void direct_link_script(FileData *UNUSED(fd), Script *script)
01560 {
01561         script->id.us = 1;
01562         SCRIPT_SET_NULL(script)
01563 }
01564 
01565 
01566 /* ************ READ PACKEDFILE *************** */
01567 
01568 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
01569 {
01570         PackedFile *pf= newdataadr(fd, oldpf);
01571 
01572         if (pf) {
01573                 pf->data= newdataadr(fd, pf->data);
01574         }
01575 
01576         return pf;
01577 }
01578 
01579 /* ************ READ IMAGE PREVIEW *************** */
01580 
01581 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
01582 {
01583         PreviewImage *prv= newdataadr(fd, old_prv);
01584 
01585         if (prv) {
01586                 int i;
01587                 for (i=0; i < NUM_ICON_SIZES; ++i) {
01588                         if (prv->rect[i]) {
01589                                 prv->rect[i] = newdataadr(fd, prv->rect[i]);
01590                         }
01591                 }
01592         }
01593 
01594         return prv;
01595 }
01596 
01597 /* ************ READ ANIMATION STUFF ***************** */
01598 
01599 /* Legacy Data Support (for Version Patching) ----------------------------- */
01600 
01601 // XXX depreceated - old animation system
01602 static void lib_link_ipo(FileData *fd, Main *main)
01603 {
01604         Ipo *ipo;
01605 
01606         ipo= main->ipo.first;
01607         while(ipo) {
01608                 if(ipo->id.flag & LIB_NEEDLINK) {
01609                         IpoCurve *icu;
01610                         for(icu= ipo->curve.first; icu; icu= icu->next) {
01611                                 if(icu->driver)
01612                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
01613                         }
01614                         ipo->id.flag -= LIB_NEEDLINK;
01615                 }
01616                 ipo= ipo->id.next;
01617         }
01618 }
01619 
01620 // XXX depreceated - old animation system
01621 static void direct_link_ipo(FileData *fd, Ipo *ipo)
01622 {
01623         IpoCurve *icu;
01624 
01625         link_list(fd, &(ipo->curve));
01626         icu= ipo->curve.first;
01627         while(icu) {
01628                 icu->bezt= newdataadr(fd, icu->bezt);
01629                 icu->bp= newdataadr(fd, icu->bp);
01630                 icu->driver= newdataadr(fd, icu->driver);
01631                 icu= icu->next;
01632         }
01633 }
01634 
01635 // XXX depreceated - old animation system
01636 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
01637 {
01638         bActionStrip *strip;
01639         bActionModifier *amod;
01640         
01641         for (strip=striplist->first; strip; strip=strip->next){
01642                 strip->object = newlibadr(fd, id->lib, strip->object);
01643                 strip->act = newlibadr_us(fd, id->lib, strip->act);
01644                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
01645                 for(amod= strip->modifiers.first; amod; amod= amod->next)
01646                         amod->ob= newlibadr(fd, id->lib, amod->ob);
01647         }
01648 }
01649 
01650 // XXX depreceated - old animation system
01651 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
01652 {
01653         bActionStrip *strip;
01654         
01655         link_list(fd, strips);
01656         
01657         for(strip= strips->first; strip; strip= strip->next)
01658                 link_list(fd, &strip->modifiers);
01659 }
01660 
01661 // XXX depreceated - old animation system
01662 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
01663 {
01664         bConstraintChannel *chan;
01665 
01666         for (chan=chanbase->first; chan; chan=chan->next){
01667                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
01668         }
01669 }
01670 
01671 /* Data Linking ----------------------------- */
01672 
01673 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
01674 {
01675         FModifier *fcm;
01676         
01677         for (fcm= list->first; fcm; fcm= fcm->next) {
01678                 /* data for specific modifiers */
01679                 switch (fcm->type) {
01680                         case FMODIFIER_TYPE_PYTHON:
01681                         {
01682                                 FMod_Python *data= (FMod_Python *)fcm->data;
01683                                 data->script = newlibadr(fd, id->lib, data->script);
01684                         }
01685                                 break;
01686                 }
01687         }
01688 }
01689 
01690 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
01691 {
01692         FCurve *fcu;
01693         
01694         if (list == NULL)
01695                 return;
01696         
01697         /* relink ID-block references... */
01698         for (fcu= list->first; fcu; fcu= fcu->next) {
01699                 /* driver data */
01700                 if (fcu->driver) {
01701                         ChannelDriver *driver= fcu->driver;
01702                         DriverVar *dvar;
01703                         
01704                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
01705                                 DRIVER_TARGETS_LOOPER(dvar)
01706                                 {       
01707                                         /* only relink if still used */
01708                                         if (tarIndex < dvar->num_targets)
01709                                                 dtar->id= newlibadr(fd, id->lib, dtar->id); 
01710                                         else
01711                                                 dtar->id= NULL;
01712                                 }
01713                                 DRIVER_TARGETS_LOOPER_END
01714                         }
01715                 }
01716                 
01717                 /* modifiers */
01718                 lib_link_fmodifiers(fd, id, &fcu->modifiers);
01719         }
01720 }
01721 
01722 
01723 /* NOTE: this assumes that link_list has already been called on the list */
01724 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
01725 {
01726         FModifier *fcm;
01727         
01728         for (fcm= list->first; fcm; fcm= fcm->next) {
01729                 /* relink general data */
01730                 fcm->data = newdataadr(fd, fcm->data);
01731                 fcm->edata= NULL;
01732                 
01733                 /* do relinking of data for specific types */
01734                 switch (fcm->type) {
01735                         case FMODIFIER_TYPE_GENERATOR:
01736                         {
01737                                 FMod_Generator *data= (FMod_Generator *)fcm->data;
01738                                 
01739                                 data->coefficients= newdataadr(fd, data->coefficients);
01740 
01741                                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
01742                                         unsigned int a;
01743                                         for(a = 0; a < data->arraysize; a++)
01744                                                 SWITCH_INT(data->coefficients[a]);
01745                                 }
01746                         }
01747                                 break;
01748                         case FMODIFIER_TYPE_ENVELOPE:
01749                         {
01750                                 FMod_Envelope *data= (FMod_Envelope *)fcm->data;
01751                                 
01752                                 data->data= newdataadr(fd, data->data);
01753                         }
01754                                 break;
01755                         case FMODIFIER_TYPE_PYTHON:
01756                         {
01757                                 FMod_Python *data= (FMod_Python *)fcm->data;
01758                                 
01759                                 data->prop = newdataadr(fd, data->prop);
01760                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
01761                         }
01762                                 break;
01763                 }
01764         }
01765 }
01766 
01767 /* NOTE: this assumes that link_list has already been called on the list */
01768 static void direct_link_fcurves(FileData *fd, ListBase *list)
01769 {
01770         FCurve *fcu;
01771         
01772         /* link F-Curve data to F-Curve again (non ID-libs) */
01773         for (fcu= list->first; fcu; fcu= fcu->next) {
01774                 /* curve data */
01775                 fcu->bezt= newdataadr(fd, fcu->bezt);
01776                 fcu->fpt= newdataadr(fd, fcu->fpt);
01777                 
01778                 /* rna path */
01779                 fcu->rna_path= newdataadr(fd, fcu->rna_path);
01780                 
01781                 /* group */
01782                 fcu->grp= newdataadr(fd, fcu->grp);
01783                 
01784                 /* driver */
01785                 fcu->driver= newdataadr(fd, fcu->driver);
01786                 if (fcu->driver) {
01787                         ChannelDriver *driver= fcu->driver;
01788                         DriverVar *dvar;
01789 
01790                         driver->expr_comp= NULL;
01791                         
01792                         /* relink variables, targets and their paths */
01793                         link_list(fd, &driver->variables);
01794                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
01795                                 DRIVER_TARGETS_LOOPER(dvar)
01796                                 {
01797                                         /* only relink the targets being used */
01798                                         if (tarIndex < dvar->num_targets)
01799                                                 dtar->rna_path= newdataadr(fd, dtar->rna_path);
01800                                         else
01801                                                 dtar->rna_path= NULL;
01802                                 }
01803                                 DRIVER_TARGETS_LOOPER_END
01804                         }
01805                 }
01806                 
01807                 /* modifiers */
01808                 link_list(fd, &fcu->modifiers);
01809                 direct_link_fmodifiers(fd, &fcu->modifiers);
01810         }
01811 }
01812 
01813 
01814 static void lib_link_action(FileData *fd, Main *main)
01815 {
01816         bAction *act;
01817         bActionChannel *chan;
01818 
01819         for (act= main->action.first; act; act= act->id.next) {
01820                 if (act->id.flag & LIB_NEEDLINK) {
01821                         act->id.flag -= LIB_NEEDLINK;
01822                         
01823 // XXX depreceated - old animation system <<<
01824                         for (chan=act->chanbase.first; chan; chan=chan->next) {
01825                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
01826                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
01827                         }
01828 // >>> XXX depreceated - old animation system
01829                         
01830                         lib_link_fcurves(fd, &act->id, &act->curves);
01831                 }
01832         }
01833 }
01834 
01835 static void direct_link_action(FileData *fd, bAction *act)
01836 {
01837         bActionChannel *achan; // XXX depreceated - old animation system
01838         bActionGroup *agrp;
01839 
01840         link_list(fd, &act->curves);
01841         link_list(fd, &act->chanbase); // XXX depreceated - old animation system
01842         link_list(fd, &act->groups);
01843         link_list(fd, &act->markers);
01844 
01845 // XXX depreceated - old animation system <<<
01846         for (achan = act->chanbase.first; achan; achan=achan->next) {
01847                 achan->grp= newdataadr(fd, achan->grp);
01848                 
01849                 link_list(fd, &achan->constraintChannels);
01850         }
01851 // >>> XXX depreceated - old animation system
01852 
01853         direct_link_fcurves(fd, &act->curves);
01854         
01855         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
01856                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
01857                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
01858         }
01859 }
01860 
01861 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
01862 {
01863         NlaStrip *strip;
01864         
01865         for (strip= list->first; strip; strip= strip->next) {
01866                 /* check strip's children */
01867                 lib_link_nladata_strips(fd, id, &strip->strips);
01868                 
01869                 /* check strip's F-Curves */
01870                 lib_link_fcurves(fd, id, &strip->fcurves);
01871                 
01872                 /* reassign the counted-reference to action */
01873                 strip->act = newlibadr_us(fd, id->lib, strip->act);
01874                 
01875                 /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */
01876                 if ((strip->act) && (strip->act->idroot == 0))
01877                         strip->act->idroot = GS(id->name);
01878         }
01879 }
01880 
01881 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
01882 {
01883         NlaTrack *nlt;
01884         
01885         /* we only care about the NLA strips inside the tracks */
01886         for (nlt= list->first; nlt; nlt= nlt->next) {
01887                 lib_link_nladata_strips(fd, id, &nlt->strips);
01888         }
01889 }
01890 
01891 /* This handles Animato NLA-Strips linking 
01892  * NOTE: this assumes that link_list has already been called on the list 
01893  */
01894 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
01895 {
01896         NlaStrip *strip;
01897         
01898         for (strip= list->first; strip; strip= strip->next) {
01899                 /* strip's child strips */
01900                 link_list(fd, &strip->strips);
01901                 direct_link_nladata_strips(fd, &strip->strips);
01902                 
01903                 /* strip's F-Curves */
01904                 link_list(fd, &strip->fcurves);
01905                 direct_link_fcurves(fd, &strip->fcurves);
01906                 
01907                 /* strip's F-Modifiers */
01908                 link_list(fd, &strip->modifiers);
01909                 direct_link_modifiers(fd, &strip->modifiers);
01910         }
01911 }
01912 
01913 /* NOTE: this assumes that link_list has already been called on the list */
01914 static void direct_link_nladata(FileData *fd, ListBase *list)
01915 {
01916         NlaTrack *nlt;
01917         
01918         for (nlt= list->first; nlt; nlt= nlt->next) {
01919                 /* relink list of strips */
01920                 link_list(fd, &nlt->strips);
01921                 
01922                 /* relink strip data */
01923                 direct_link_nladata_strips(fd, &nlt->strips);
01924         }
01925 }
01926 
01927 /* ------- */
01928 
01929 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
01930 {
01931         KeyingSet *ks;
01932         KS_Path *ksp;
01933         
01934         /* here, we're only interested in the ID pointer stored in some of the paths */
01935         for (ks= list->first; ks; ks= ks->next) {
01936                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
01937                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
01938                 }
01939         }
01940 }
01941 
01942 /* NOTE: this assumes that link_list has already been called on the list */
01943 static void direct_link_keyingsets(FileData *fd, ListBase *list)
01944 {
01945         KeyingSet *ks;
01946         KS_Path *ksp;
01947         
01948         /* link KeyingSet data to KeyingSet again (non ID-libs) */
01949         for (ks= list->first; ks; ks= ks->next) {
01950                 /* paths */
01951                 link_list(fd, &ks->paths);
01952                 
01953                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
01954                         /* rna path */
01955                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
01956                 }
01957         }
01958 }
01959 
01960 /* ------- */
01961 
01962 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
01963 {
01964         if (adt == NULL)
01965                 return;
01966         
01967         /* link action data */
01968         adt->action= newlibadr_us(fd, id->lib, adt->action);
01969         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
01970         
01971         /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */
01972         if ((adt->action) && (adt->action->idroot == 0))
01973                 adt->action->idroot = GS(id->name);
01974         if ((adt->tmpact) && (adt->tmpact->idroot == 0))
01975                 adt->tmpact->idroot = GS(id->name);
01976         
01977         /* link drivers */
01978         lib_link_fcurves(fd, id, &adt->drivers);
01979         
01980         /* overrides don't have lib-link for now, so no need to do anything */
01981         
01982         /* link NLA-data */
01983         lib_link_nladata(fd, id, &adt->nla_tracks);
01984 }
01985 
01986 static void direct_link_animdata(FileData *fd, AnimData *adt)
01987 {
01988         /* NOTE: must have called newdataadr already before doing this... */
01989         if (adt == NULL)
01990                 return;
01991         
01992         /* link drivers */
01993         link_list(fd, &adt->drivers);
01994         direct_link_fcurves(fd, &adt->drivers);
01995         
01996         /* link overrides */
01997         // TODO...
01998         
01999         /* link NLA-data */
02000         link_list(fd, &adt->nla_tracks);
02001         direct_link_nladata(fd, &adt->nla_tracks);
02002         
02003         /* relink active strip - even though strictly speaking this should only be used
02004          * if we're in 'tweaking mode', we need to be able to have this loaded back for
02005          * undo, but also since users may not exit tweakmode before saving (#24535)
02006          */
02007         // TODO: it's not really nice that anyone should be able to save the file in this
02008         //              state, but it's going to be too hard to enforce this single case...
02009         adt->actstrip= newdataadr(fd, adt->actstrip);
02010 }       
02011 
02012 /* ************ READ MOTION PATHS *************** */
02013 
02014 /* direct data for cache */
02015 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
02016 {
02017         /* sanity check */
02018         if (mpath == NULL)
02019                 return;
02020         
02021         /* relink points cache */
02022         mpath->points= newdataadr(fd, mpath->points);
02023 }
02024 
02025 /* ************ READ NODE TREE *************** */
02026 
02027 /* singe node tree (also used for material/scene trees), ntree is not NULL */
02028 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
02029 {
02030         bNode *node;
02031         
02032         if(ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
02033         
02034         ntree->gpd= newlibadr_us(fd, id->lib, ntree->gpd);
02035         
02036         for(node= ntree->nodes.first; node; node= node->next)
02037                 node->id= newlibadr_us(fd, id->lib, node->id);
02038 }
02039 
02040 /* library ntree linking after fileread */
02041 static void lib_link_nodetree(FileData *fd, Main *main)
02042 {
02043         bNodeTree *ntree;
02044         
02045         /* only link ID pointers */
02046         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
02047                 if(ntree->id.flag & LIB_NEEDLINK) {
02048                         ntree->id.flag -= LIB_NEEDLINK;
02049                         lib_link_ntree(fd, &ntree->id, ntree);
02050                 }
02051         }
02052 }
02053 
02054 /* updates group node socket own_index so that
02055  * external links to/from the group node are preserved.
02056  */
02057 static void lib_node_do_versions_group(bNode *gnode)
02058 {
02059         bNodeTree *ngroup= (bNodeTree*)gnode->id;
02060         bNode *intnode;
02061         bNodeSocket *sock, *gsock, *intsock;
02062         int found;
02063         
02064         for (sock=gnode->outputs.first; sock; sock=sock->next) {
02065                 int old_index = sock->to_index;
02066                 for (gsock=ngroup->outputs.first; gsock; gsock=gsock->next) {
02067                         if (gsock->link && gsock->link->fromsock->own_index == old_index) {
02068                                 sock->own_index = gsock->own_index;
02069                                 break;
02070                         }
02071                 }
02072         }
02073         for (sock=gnode->inputs.first; sock; sock=sock->next) {
02074                 int old_index = sock->to_index;
02075                 /* can't use break in double loop */
02076                 found = 0;
02077                 for (intnode=ngroup->nodes.first; intnode && !found; intnode=intnode->next) {
02078                         for (intsock=intnode->inputs.first; intsock; intsock=intsock->next) {
02079                                 if (intsock->own_index == old_index && intsock->link) {
02080                                         sock->own_index = intsock->link->fromsock->own_index;
02081                                         found = 1;
02082                                         break;
02083                                 }
02084                         }
02085                 }
02086         }
02087 }
02088 
02089 /* updates external links for all group nodes in a tree */
02090 static void lib_nodetree_do_versions_group(bNodeTree *ntree)
02091 {
02092         bNode *node;
02093         
02094         for (node=ntree->nodes.first; node; node=node->next) {
02095                 if (node->type==NODE_GROUP) {
02096                         bNodeTree *ngroup= (bNodeTree*)node->id;
02097                         if (ngroup && (ngroup->flag & NTREE_DO_VERSIONS))
02098                                 lib_node_do_versions_group(node);
02099                 }
02100         }
02101 }
02102 
02103 /* verify types for nodes and groups, all data has to be read */
02104 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
02105 * typedefs*/
02106 static void lib_verify_nodetree(Main *main, int UNUSED(open))
02107 {
02108         Scene *sce;
02109         Material *ma;
02110         Tex *tx;
02111         bNodeTree *ntree;
02112         
02113         /* this crashes blender on undo/redo
02114                 if(open==1) {
02115                         reinit_nodesystem();
02116                 }*/
02117         
02118         /* now create the own typeinfo structs an verify nodes */
02119         /* here we still assume no groups in groups */
02120         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
02121                 ntreeVerifyTypes(ntree);                /* internal nodes, no groups! */
02122         }
02123         
02124         {
02125                 /*int has_old_groups=0;*/ /*UNUSED*/
02126                 /* XXX this should actually be part of do_versions, but since we need
02127                  * finished library linking, it is not possible there. Instead in do_versions
02128                  * we have set the NTREE_DO_VERSIONS flag, so at this point we can do the
02129                  * actual group node updates.
02130                  */
02131                 for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
02132                         if (ntree->flag & NTREE_DO_VERSIONS) {
02133                                 /* this adds copies and links from all unlinked internal sockets to group inputs/outputs. */
02134                                 nodeGroupExposeAllSockets(ntree);
02135                                 /*has_old_groups = 1;*/ /*UNUSED*/
02136                         }
02137                 }
02138                 /* now verify all types in material trees, groups are set OK now */
02139                 for(ma= main->mat.first; ma; ma= ma->id.next) {
02140                         if(ma->nodetree)
02141                                 lib_nodetree_do_versions_group(ma->nodetree);
02142                 }
02143                 /* and scene trees */
02144                 for(sce= main->scene.first; sce; sce= sce->id.next) {
02145                         if(sce->nodetree)
02146                                 lib_nodetree_do_versions_group(sce->nodetree);
02147                 }
02148                 /* and texture trees */
02149                 for(tx= main->tex.first; tx; tx= tx->id.next) {
02150                         if(tx->nodetree)
02151                                 lib_nodetree_do_versions_group(tx->nodetree);
02152                 }
02153                 
02154                 for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
02155                         ntree->flag &= ~NTREE_DO_VERSIONS;
02156         }
02157 
02158         /* now verify all types in material trees, groups are set OK now */
02159         for(ma= main->mat.first; ma; ma= ma->id.next) {
02160                 if(ma->nodetree)
02161                         ntreeVerifyTypes(ma->nodetree);
02162         }
02163         /* and scene trees */
02164         for(sce= main->scene.first; sce; sce= sce->id.next) {
02165                 if(sce->nodetree)
02166                         ntreeVerifyTypes(sce->nodetree);
02167         }
02168         /* and texture trees */
02169         for(tx= main->tex.first; tx; tx= tx->id.next) {
02170                 if(tx->nodetree)
02171                         ntreeVerifyTypes(tx->nodetree);
02172         }
02173 }
02174 
02175 
02176 
02177 /* ntree itself has been read! */
02178 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
02179 {
02180         /* note: writing and reading goes in sync, for speed */
02181         bNode *node;
02182         bNodeSocket *sock;
02183         bNodeLink *link;
02184         
02185         ntree->init= 0;         /* to set callbacks and force setting types */
02186         ntree->progress= NULL;
02187         
02188         ntree->adt= newdataadr(fd, ntree->adt);
02189         direct_link_animdata(fd, ntree->adt);
02190         
02191         link_list(fd, &ntree->nodes);
02192         for(node= ntree->nodes.first; node; node= node->next) {
02193                 if(node->type == NODE_DYNAMIC) {
02194                         node->custom1= 0;
02195                         node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
02196                         node->typeinfo= NULL;
02197                 }
02198                 
02199                 node->storage= newdataadr(fd, node->storage);
02200                 if(node->storage) {
02201                         
02202                         /* could be handlerized at some point */
02203                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
02204                                 direct_link_curvemapping(fd, node->storage);
02205                         else if(ntree->type==NTREE_COMPOSIT) {
02206                                 if( ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
02207                                         direct_link_curvemapping(fd, node->storage);
02208                                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
02209                                         ((ImageUser *)node->storage)->ok= 1;
02210                         }
02211                         else if( ntree->type==NTREE_TEXTURE) {
02212                                 if(node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
02213                                         direct_link_curvemapping(fd, node->storage);
02214                                 else if(node->type==TEX_NODE_IMAGE)
02215                                         ((ImageUser *)node->storage)->ok= 1;
02216                         }
02217                 }
02218                 link_list(fd, &node->inputs);
02219                 link_list(fd, &node->outputs);
02220         }
02221         link_list(fd, &ntree->links);
02222         
02223         /* external sockets */
02224         link_list(fd, &ntree->inputs);
02225         link_list(fd, &ntree->outputs);
02226         
02227         /* and we connect the rest */
02228         for(node= ntree->nodes.first; node; node= node->next) {
02229                 node->preview= newimaadr(fd, node->preview);
02230                 node->lasty= 0;
02231                 for(sock= node->inputs.first; sock; sock= sock->next)
02232                         sock->link= newdataadr(fd, sock->link);
02233                 for(sock= node->outputs.first; sock; sock= sock->next)
02234                         sock->ns.data= NULL;
02235         }
02236         for(sock= ntree->outputs.first; sock; sock= sock->next)
02237                 sock->link= newdataadr(fd, sock->link);
02238         
02239         for(link= ntree->links.first; link; link= link->next) {
02240                 link->fromnode= newdataadr(fd, link->fromnode);
02241                 link->tonode= newdataadr(fd, link->tonode);
02242                 link->fromsock= newdataadr(fd, link->fromsock);
02243                 link->tosock= newdataadr(fd, link->tosock);
02244         }
02245         
02246         /* type verification is in lib-link */
02247 }
02248 
02249 /* ************ READ ARMATURE ***************** */
02250 
02251 /* temp struct used to transport needed info to lib_link_constraint_cb() */
02252 typedef struct tConstraintLinkData {
02253         FileData *fd;
02254         ID *id;
02255 } tConstraintLinkData;
02256 /* callback function used to relink constraint ID-links */
02257 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, void *userdata)
02258 {
02259         tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
02260         *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
02261 }
02262 
02263 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
02264 {
02265         tConstraintLinkData cld;
02266         bConstraint *con;
02267         
02268         /* legacy fixes */
02269         for (con = conlist->first; con; con=con->next) {
02270                 /* patch for error introduced by changing constraints (dunno how) */
02271                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
02272                 if(con->data==NULL) {
02273                         con->type= CONSTRAINT_TYPE_NULL;
02274                 }
02275                 /* own ipo, all constraints have it */
02276                 con->ipo= newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
02277         }
02278         
02279         /* relink all ID-blocks used by the constraints */
02280         cld.fd= fd;
02281         cld.id= id;
02282         
02283         id_loop_constraints(conlist, lib_link_constraint_cb, &cld);
02284 }
02285 
02286 static void direct_link_constraints(FileData *fd, ListBase *lb)
02287 {
02288         bConstraint *con;
02289 
02290         link_list(fd, lb);
02291         for (con=lb->first; con; con=con->next) {
02292                 con->data = newdataadr(fd, con->data);
02293                 
02294                 switch (con->type) {
02295                         case CONSTRAINT_TYPE_PYTHON:
02296                         {
02297                                 bPythonConstraint *data= con->data;
02298                                 
02299                                 link_list(fd, &data->targets);
02300                                 
02301                                 data->prop = newdataadr(fd, data->prop);
02302                                 if (data->prop)
02303                                         IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
02304                         }
02305                                 break;
02306                         case CONSTRAINT_TYPE_SPLINEIK:
02307                         {
02308                                 bSplineIKConstraint *data= con->data;
02309                                 
02310                                 data->points= newdataadr(fd, data->points);
02311                         }
02312                                 break;
02313                         case CONSTRAINT_TYPE_KINEMATIC:
02314                         {
02315                                 con->lin_error = 0.f;
02316                                 con->rot_error = 0.f;
02317                         }
02318                         case CONSTRAINT_TYPE_CHILDOF:
02319                         {
02320                                 /* XXX version patch, in older code this flag wasn't always set, and is inherent to type */
02321                                 if(con->ownspace == CONSTRAINT_SPACE_POSE)
02322                                         con->flag |= CONSTRAINT_SPACEONCE;
02323                         }
02324                                 break;
02325                 }
02326         }
02327 }
02328 
02329 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
02330 {
02331         bPoseChannel *pchan;
02332         bArmature *arm= ob->data;
02333         int rebuild;
02334         
02335         if (!pose || !arm)
02336                 return;
02337         
02338 
02339         /* always rebuild to match proxy or lib changes */
02340         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
02341 
02342         if(ob->proxy) {
02343                 /* sync proxy layer */
02344                 if(pose->proxy_layer)
02345                         arm->layer = pose->proxy_layer;
02346                 
02347                 /* sync proxy active bone */
02348                 if(pose->proxy_act_bone[0]) {
02349                         Bone *bone = get_named_bone(arm, pose->proxy_act_bone);
02350                         if (bone)
02351                                 arm->act_bone = bone;
02352                 }
02353         }
02354 
02355         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
02356                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
02357                 
02358                 /* hurms... loop in a loop, but yah... later... (ton) */
02359                 pchan->bone= get_named_bone(arm, pchan->name);
02360                 
02361                 pchan->custom= newlibadr_us(fd, arm->id.lib, pchan->custom);
02362                 if(pchan->bone==NULL)
02363                         rebuild= 1;
02364                 else if(ob->id.lib==NULL && arm->id.lib) {
02365                         /* local pose selection copied to armature, bit hackish */
02366                         pchan->bone->flag &= ~BONE_SELECTED;
02367                         pchan->bone->flag |= pchan->selectflag;
02368                 }
02369         }
02370         
02371         if(rebuild) {
02372                 ob->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
02373                 pose->flag |= POSE_RECALC;
02374         }
02375 }
02376 
02377 static void lib_link_armature(FileData *fd, Main *main)
02378 {
02379         bArmature *arm;
02380 
02381         arm= main->armature.first;
02382 
02383         while(arm) {
02384                 if(arm->id.flag & LIB_NEEDLINK) {
02385                         if (arm->adt) lib_link_animdata(fd, &arm->id, arm->adt);
02386                         arm->id.flag -= LIB_NEEDLINK;
02387                 }
02388                 arm= arm->id.next;
02389         }
02390 }
02391 
02392 static void direct_link_bones(FileData *fd, Bone* bone)
02393 {
02394         Bone    *child;
02395 
02396         bone->parent= newdataadr(fd, bone->parent);
02397         bone->prop= newdataadr(fd, bone->prop);
02398         if(bone->prop)
02399                 IDP_DirectLinkProperty(bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
02400                 
02401         bone->flag &= ~BONE_DRAW_ACTIVE;
02402 
02403         link_list(fd, &bone->childbase);
02404 
02405         for(child=bone->childbase.first; child; child=child->next)
02406                 direct_link_bones(fd, child);
02407 }
02408 
02409 static void direct_link_armature(FileData *fd, bArmature *arm)
02410 {
02411         Bone    *bone;
02412 
02413         link_list(fd, &arm->bonebase);
02414         arm->edbo= NULL;
02415         arm->sketch = NULL;
02416         
02417         arm->adt= newdataadr(fd, arm->adt);
02418         direct_link_animdata(fd, arm->adt);
02419         
02420         bone=arm->bonebase.first;
02421         while (bone) {
02422                 direct_link_bones(fd, bone);
02423                 bone=bone->next;
02424         }
02425 
02426         arm->act_bone= newdataadr(fd, arm->act_bone);
02427         arm->act_edbone= NULL;
02428 }
02429 
02430 /* ************ READ CAMERA ***************** */
02431 
02432 static void lib_link_camera(FileData *fd, Main *main)
02433 {
02434         Camera *ca;
02435 
02436         ca= main->camera.first;
02437         while(ca) {
02438                 if(ca->id.flag & LIB_NEEDLINK) {
02439                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
02440                         
02441                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
02442                         
02443                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
02444                         
02445                         ca->id.flag -= LIB_NEEDLINK;
02446                 }
02447                 ca= ca->id.next;
02448         }
02449 }
02450 
02451 static void direct_link_camera(FileData *fd, Camera *ca)
02452 {
02453         ca->adt= newdataadr(fd, ca->adt);
02454         direct_link_animdata(fd, ca->adt);
02455 }
02456 
02457 
02458 /* ************ READ LAMP ***************** */
02459 
02460 static void lib_link_lamp(FileData *fd, Main *main)
02461 {
02462         Lamp *la;
02463         MTex *mtex;
02464         int a;
02465 
02466         la= main->lamp.first;
02467         while(la) {
02468                 if(la->id.flag & LIB_NEEDLINK) {
02469                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
02470                         
02471                         for(a=0; a<MAX_MTEX; a++) {
02472                                 mtex= la->mtex[a];
02473                                 if(mtex) {
02474                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
02475                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
02476                                 }
02477                         }
02478                         
02479                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
02480                         
02481                         la->id.flag -= LIB_NEEDLINK;
02482                 }
02483                 la= la->id.next;
02484         }
02485 }
02486 
02487 static void direct_link_lamp(FileData *fd, Lamp *la)
02488 {
02489         int a;
02490         
02491         la->adt= newdataadr(fd, la->adt);
02492         direct_link_animdata(fd, la->adt);
02493 
02494         for(a=0; a<MAX_MTEX; a++) {
02495                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
02496         }
02497         
02498         la->curfalloff= newdataadr(fd, la->curfalloff);
02499         if(la->curfalloff)
02500                 direct_link_curvemapping(fd, la->curfalloff);
02501         
02502         la->preview = direct_link_preview_image(fd, la->preview);
02503 }
02504 
02505 /* ************ READ keys ***************** */
02506 
02507 static void lib_link_key(FileData *fd, Main *main)
02508 {
02509         Key *key;
02510 
02511         key= main->key.first;
02512         while(key) {
02513                 if(key->id.flag & LIB_NEEDLINK) {
02514                         if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
02515                         
02516                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
02517                         key->from= newlibadr(fd, key->id.lib, key->from);
02518 
02519                         key->id.flag -= LIB_NEEDLINK;
02520                 }
02521                 key= key->id.next;
02522         }
02523 }
02524 
02525 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
02526 {
02527         int elemsize, a, b;
02528         char *data, *poin, *cp;
02529 
02530         elemsize= key->elemsize;
02531         data= kb->data;
02532 
02533         for(a=0; a<kb->totelem; a++) {
02534 
02535                 cp= key->elemstr;
02536                 poin= data;
02537 
02538                 while( cp[0] ) {        /* cp[0]==amount */
02539 
02540                         switch(cp[1]) {         /* cp[1]= type */
02541                         case IPO_FLOAT:
02542                         case IPO_BPOINT:
02543                         case IPO_BEZTRIPLE:
02544                                 b= cp[0];
02545                                 while(b--) {
02546                                         SWITCH_INT((*poin));
02547                                         poin+= 4;
02548                                 }
02549                                 break;
02550                         }
02551 
02552                         cp+= 2;
02553 
02554                 }
02555                 data+= elemsize;
02556         }
02557 }
02558 
02559 static void direct_link_key(FileData *fd, Key *key)
02560 {
02561         KeyBlock *kb;
02562 
02563         link_list(fd, &(key->block));
02564 
02565         key->adt= newdataadr(fd, key->adt);
02566         direct_link_animdata(fd, key->adt);
02567         
02568         key->refkey= newdataadr(fd, key->refkey);
02569 
02570         kb= key->block.first;
02571         while(kb) {
02572 
02573                 kb->data= newdataadr(fd, kb->data);
02574                 
02575                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
02576                         switch_endian_keyblock(key, kb);
02577 
02578                 kb= kb->next;
02579         }
02580 }
02581 
02582 /* ************ READ mball ***************** */
02583 
02584 static void lib_link_mball(FileData *fd, Main *main)
02585 {
02586         MetaBall *mb;
02587         int a;
02588 
02589         mb= main->mball.first;
02590         while(mb) {
02591                 if(mb->id.flag & LIB_NEEDLINK) {
02592                         if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
02593                         
02594                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
02595 
02596                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
02597 
02598                         mb->id.flag -= LIB_NEEDLINK;
02599                 }
02600                 mb= mb->id.next;
02601         }
02602 }
02603 
02604 static void direct_link_mball(FileData *fd, MetaBall *mb)
02605 {
02606         mb->adt= newdataadr(fd, mb->adt);
02607         direct_link_animdata(fd, mb->adt);
02608         
02609         mb->mat= newdataadr(fd, mb->mat);
02610         test_pointer_array(fd, (void **)&mb->mat);
02611 
02612         link_list(fd, &(mb->elems));
02613 
02614         mb->disp.first= mb->disp.last= NULL;
02615         mb->editelems= NULL;
02616         mb->bb= NULL;
02617 /*      mb->edit_elems.first= mb->edit_elems.last= NULL;*/
02618         mb->lastelem= NULL;
02619 }
02620 
02621 /* ************ READ WORLD ***************** */
02622 
02623 static void lib_link_world(FileData *fd, Main *main)
02624 {
02625         World *wrld;
02626         MTex *mtex;
02627         int a;
02628 
02629         wrld= main->world.first;
02630         while(wrld) {
02631                 if(wrld->id.flag & LIB_NEEDLINK) {
02632                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
02633                         
02634                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
02635                         
02636                         for(a=0; a<MAX_MTEX; a++) {
02637                                 mtex= wrld->mtex[a];
02638                                 if(mtex) {
02639                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
02640                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
02641                                 }
02642                         }
02643                         
02644                         wrld->id.flag -= LIB_NEEDLINK;
02645                 }
02646                 wrld= wrld->id.next;
02647         }
02648 }
02649 
02650 static void direct_link_world(FileData *fd, World *wrld)
02651 {
02652         int a;
02653 
02654         wrld->adt= newdataadr(fd, wrld->adt);
02655         direct_link_animdata(fd, wrld->adt);
02656 
02657         for(a=0; a<MAX_MTEX; a++) {
02658                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
02659         }
02660         wrld->preview = direct_link_preview_image(fd, wrld->preview);
02661 }
02662 
02663 
02664 /* ************ READ VFONT ***************** */
02665 
02666 static void lib_link_vfont(FileData *UNUSED(fd), Main *main)
02667 {
02668         VFont *vf;
02669 
02670         vf= main->vfont.first;
02671         while(vf) {
02672                 if(vf->id.flag & LIB_NEEDLINK) {
02673                         vf->id.flag -= LIB_NEEDLINK;
02674                 }
02675                 vf= vf->id.next;
02676         }
02677 }
02678 
02679 static void direct_link_vfont(FileData *fd, VFont *vf)
02680 {
02681         vf->data= NULL;
02682         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
02683 }
02684 
02685 /* ************ READ TEXT ****************** */
02686 
02687 static void lib_link_text(FileData *UNUSED(fd), Main *main)
02688 {
02689         Text *text;
02690 
02691         text= main->text.first;
02692         while(text) {
02693                 if(text->id.flag & LIB_NEEDLINK) {
02694                         text->id.flag -= LIB_NEEDLINK;
02695                 }
02696                 text= text->id.next;
02697         }
02698 }
02699 
02700 static void direct_link_text(FileData *fd, Text *text)
02701 {
02702         TextLine *ln;
02703 
02704         text->name= newdataadr(fd, text->name);
02705 
02706         text->undo_pos= -1;
02707         text->undo_len= TXT_INIT_UNDO;
02708         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
02709 
02710         text->compiled= NULL;
02711 
02712 /*
02713         if(text->flags & TXT_ISEXT) {
02714                 reopen_text(text);
02715         } else {
02716 */
02717 
02718         link_list(fd, &text->lines);
02719         link_list(fd, &text->markers);
02720 
02721         text->curl= newdataadr(fd, text->curl);
02722         text->sell= newdataadr(fd, text->sell);
02723 
02724         ln= text->lines.first;
02725         while(ln) {
02726                 ln->line= newdataadr(fd, ln->line);
02727                 ln->format= NULL;
02728                 
02729                 if (ln->len != (int) strlen(ln->line)) {
02730                         printf("Error loading text, line lengths differ\n");
02731                         ln->len = strlen(ln->line);
02732                 }
02733 
02734                 ln= ln->next;
02735         }
02736 
02737         text->flags = (text->flags) & ~TXT_ISEXT;
02738 
02739         text->id.us= 1;
02740 }
02741 
02742 /* ************ READ IMAGE ***************** */
02743 
02744 static void lib_link_image(FileData *fd, Main *main)
02745 {
02746         Image *ima;
02747 
02748         ima= main->image.first;
02749         while (ima) {
02750                 if(ima->id.flag & LIB_NEEDLINK) {
02751                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
02752 
02753                         ima->id.flag -= LIB_NEEDLINK;
02754                 }
02755                 ima= ima->id.next;
02756         }
02757 }
02758 
02759 static void link_ibuf_list(FileData *fd, ListBase *lb)
02760 {
02761         Link *ln, *prev;
02762         
02763         if(lb->first==NULL) return;
02764         
02765         lb->first= newimaadr(fd, lb->first);
02766         ln= lb->first;
02767         prev= NULL;
02768         while(ln) {
02769                 ln->next= newimaadr(fd, ln->next);
02770                 ln->prev= prev;
02771                 prev= ln;
02772                 ln= ln->next;
02773         }
02774         lb->last= prev;
02775 }
02776 
02777 static void direct_link_image(FileData *fd, Image *ima)
02778 {
02779         /* for undo system, pointers could be restored */
02780         if(fd->imamap)
02781                 link_ibuf_list(fd, &ima->ibufs);
02782         else
02783                 ima->ibufs.first= ima->ibufs.last= NULL;
02784         
02785         /* if not restored, we keep the binded opengl index */
02786         if(ima->ibufs.first==NULL) {
02787                 ima->bindcode= 0;
02788                 ima->gputexture= NULL;
02789         }
02790         
02791         ima->anim= NULL;
02792         ima->rr= NULL;
02793         ima->repbind= NULL;
02794         
02795         /* undo system, try to restore render buffers */
02796         if(fd->imamap) {
02797                 int a;
02798                 
02799                 for(a=0; a<IMA_MAX_RENDER_SLOT; a++)
02800                         ima->renders[a]= newimaadr(fd, ima->renders[a]);
02801         }
02802         else {
02803                 memset(ima->renders, 0, sizeof(ima->renders));
02804                 ima->last_render_slot= ima->render_slot;
02805         }
02806         
02807         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
02808         ima->preview = direct_link_preview_image(fd, ima->preview);
02809         ima->ok= 1;
02810 }
02811 
02812 
02813 /* ************ READ CURVE ***************** */
02814 
02815 static void lib_link_curve(FileData *fd, Main *main)
02816 {
02817         Curve *cu;
02818         int a;
02819 
02820         cu= main->curve.first;
02821         while(cu) {
02822                 if(cu->id.flag & LIB_NEEDLINK) {
02823                         if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
02824 
02825                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
02826 
02827                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
02828                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
02829                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
02830                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
02831                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
02832                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
02833                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
02834 
02835                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
02836                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
02837 
02838                         cu->id.flag -= LIB_NEEDLINK;
02839                 }
02840                 cu= cu->id.next;
02841         }
02842 }
02843 
02844 
02845 static void switch_endian_knots(Nurb *nu)
02846 {
02847         int len;
02848 
02849         if(nu->knotsu) {
02850                 len= KNOTSU(nu);
02851                 while(len--) {
02852                         SWITCH_INT(nu->knotsu[len]);
02853                 }
02854         }
02855         if(nu->knotsv) {
02856                 len= KNOTSV(nu);
02857                 while(len--) {
02858                         SWITCH_INT(nu->knotsv[len]);
02859                 }
02860         }
02861 }
02862 
02863 static void direct_link_curve(FileData *fd, Curve *cu)
02864 {
02865         Nurb *nu;
02866         TextBox *tb;
02867         
02868         cu->adt= newdataadr(fd, cu->adt);
02869         direct_link_animdata(fd, cu->adt);
02870         
02871         cu->mat= newdataadr(fd, cu->mat);
02872         test_pointer_array(fd, (void **)&cu->mat);
02873         cu->str= newdataadr(fd, cu->str);
02874         cu->strinfo= newdataadr(fd, cu->strinfo);       
02875         cu->tb= newdataadr(fd, cu->tb);
02876 
02877         if(cu->vfont == NULL) link_list(fd, &(cu->nurb));
02878         else {
02879                 cu->nurb.first=cu->nurb.last= NULL;
02880 
02881                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
02882                 if (cu->tb) {
02883                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
02884                         MEM_freeN(cu->tb);
02885                         cu->tb= tb;                     
02886                 } else {
02887                         cu->totbox = 1;
02888                         cu->actbox = 1;
02889                         cu->tb = tb;
02890                         cu->tb[0].w = cu->linewidth;
02891                 }               
02892                 if (cu->wordspace == 0.0f) cu->wordspace = 1.0f;
02893         }
02894 
02895         cu->bev.first=cu->bev.last= NULL;
02896         cu->disp.first=cu->disp.last= NULL;
02897         cu->editnurb= NULL;
02898         cu->lastsel= NULL;
02899         cu->path= NULL;
02900         cu->editfont= NULL;
02901         
02902         nu= cu->nurb.first;
02903         while(nu) {
02904                 nu->bezt= newdataadr(fd, nu->bezt);
02905                 nu->bp= newdataadr(fd, nu->bp);
02906                 nu->knotsu= newdataadr(fd, nu->knotsu);
02907                 nu->knotsv= newdataadr(fd, nu->knotsv);
02908                 if (cu->vfont == NULL) nu->charidx= nu->mat_nr;
02909 
02910                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
02911                         switch_endian_knots(nu);
02912                 }
02913 
02914                 nu= nu->next;
02915         }
02916         cu->bb= NULL;
02917 }
02918 
02919 /* ************ READ TEX ***************** */
02920 
02921 static void lib_link_texture(FileData *fd, Main *main)
02922 {
02923         Tex *tex;
02924 
02925         tex= main->tex.first;
02926         while(tex) {
02927                 if(tex->id.flag & LIB_NEEDLINK) {
02928                         if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
02929 
02930                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
02931                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
02932                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
02933                         if(tex->pd)
02934                                 tex->pd->object= newlibadr(fd, tex->id.lib, tex->pd->object);
02935                         if(tex->vd) tex->vd->object= newlibadr(fd, tex->id.lib, tex->vd->object);
02936 
02937                         if(tex->nodetree)
02938                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
02939                         
02940                         tex->id.flag -= LIB_NEEDLINK;
02941                 }
02942                 tex= tex->id.next;
02943         }
02944 }
02945 
02946 static void direct_link_texture(FileData *fd, Tex *tex)
02947 {
02948         tex->adt= newdataadr(fd, tex->adt);
02949         direct_link_animdata(fd, tex->adt);
02950         
02951         tex->plugin= newdataadr(fd, tex->plugin);
02952         if(tex->plugin) {
02953                 tex->plugin->handle= NULL;
02954                 open_plugin_tex(tex->plugin);
02955                 /* initialize data for this instance, if an initialization
02956                  * function exists.
02957                  */
02958                 if (tex->plugin->instance_init)
02959                         tex->plugin->instance_init((void *) tex->plugin->data);
02960         }
02961         tex->coba= newdataadr(fd, tex->coba);
02962         tex->env= newdataadr(fd, tex->env);
02963         if(tex->env) {
02964                 tex->env->ima= NULL;
02965                 memset(tex->env->cube, 0, 6*sizeof(void *));
02966                 tex->env->ok= 0;
02967         }
02968         tex->pd= newdataadr(fd, tex->pd);
02969         if(tex->pd) {
02970                 tex->pd->point_tree = NULL;
02971                 tex->pd->coba= newdataadr(fd, tex->pd->coba);
02972                 tex->pd->falloff_curve= newdataadr(fd, tex->pd->falloff_curve);
02973                 if(tex->pd->falloff_curve) {
02974                         direct_link_curvemapping(fd, tex->pd->falloff_curve);
02975                 }
02976         }
02977         
02978         tex->vd= newdataadr(fd, tex->vd);
02979         if(tex->vd) {
02980                 tex->vd->dataset = NULL;
02981                 tex->vd->ok = 0;
02982         }
02983         
02984         tex->nodetree= newdataadr(fd, tex->nodetree);
02985         if(tex->nodetree)
02986                 direct_link_nodetree(fd, tex->nodetree);
02987         
02988         tex->preview = direct_link_preview_image(fd, tex->preview);
02989 
02990         tex->iuser.ok= 1;
02991 }
02992 
02993 
02994 
02995 /* ************ READ MATERIAL ***************** */
02996 
02997 static void lib_link_material(FileData *fd, Main *main)
02998 {
02999         Material *ma;
03000         MTex *mtex;
03001         int a;
03002 
03003         ma= main->mat.first;
03004         while(ma) {
03005                 if(ma->id.flag & LIB_NEEDLINK) {
03006                         if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
03007 
03008                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
03009                         of library blocks that implement this.*/
03010                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
03011 
03012                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
03013                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
03014                         
03015                         for(a=0; a<MAX_MTEX; a++) {
03016                                 mtex= ma->mtex[a];
03017                                 if(mtex) {
03018                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
03019                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
03020                                 }
03021                         }
03022                         
03023                         if(ma->nodetree)
03024                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
03025                         
03026                         ma->id.flag -= LIB_NEEDLINK;
03027                 }
03028                 ma= ma->id.next;
03029         }
03030 }
03031 
03032 static void direct_link_material(FileData *fd, Material *ma)
03033 {
03034         int a;
03035 
03036         ma->adt= newdataadr(fd, ma->adt);
03037         direct_link_animdata(fd, ma->adt);
03038         
03039         for(a=0; a<MAX_MTEX; a++) {
03040                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
03041         }
03042 
03043         ma->ramp_col= newdataadr(fd, ma->ramp_col);
03044         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
03045         
03046         ma->nodetree= newdataadr(fd, ma->nodetree);
03047         if(ma->nodetree)
03048                 direct_link_nodetree(fd, ma->nodetree);
03049 
03050         ma->preview = direct_link_preview_image(fd, ma->preview);
03051         ma->gpumaterial.first = ma->gpumaterial.last = NULL;
03052 }
03053 
03054 /* ************ READ PARTICLE SETTINGS ***************** */
03055 /* update this also to writefile.c */
03056 static const char *ptcache_data_struct[] = {
03057         "", // BPHYS_DATA_INDEX
03058         "", // BPHYS_DATA_LOCATION
03059         "", // BPHYS_DATA_VELOCITY
03060         "", // BPHYS_DATA_ROTATION
03061         "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
03062         "", // BPHYS_DATA_SIZE:
03063         "", // BPHYS_DATA_TIMES:        
03064         "BoidData" // case BPHYS_DATA_BOIDS:
03065 };
03066 static void direct_link_pointcache(FileData *fd, PointCache *cache)
03067 {
03068         if((cache->flag & PTCACHE_DISK_CACHE)==0) {
03069                 PTCacheMem *pm;
03070                 PTCacheExtra *extra;
03071                 int i;
03072 
03073                 link_list(fd, &cache->mem_cache);
03074 
03075                 pm = cache->mem_cache.first;
03076 
03077                 for(; pm; pm=pm->next) {
03078                         for(i=0; i<BPHYS_TOT_DATA; i++) {
03079                                 pm->data[i] = newdataadr(fd, pm->data[i]);
03080                                 
03081                                 /* the cache saves non-struct data without DNA */
03082                                 if(pm->data[i] && strcmp(ptcache_data_struct[i], "")==0 && (fd->flags & FD_FLAGS_SWITCH_ENDIAN)) {
03083                                         int j, tot= (BKE_ptcache_data_size (i) * pm->totpoint)/4; /* data_size returns bytes */
03084                                         int *poin= pm->data[i];
03085                                         
03086                                         for(j= 0; j<tot; j++)
03087                                                 SWITCH_INT(poin[j]);
03088                                 }
03089                         }
03090                         
03091                         link_list(fd, &pm->extradata);
03092 
03093                         for(extra=pm->extradata.first; extra; extra=extra->next)
03094                                 extra->data = newdataadr(fd, extra->data);
03095                 }
03096         }
03097         else
03098                 cache->mem_cache.first = cache->mem_cache.last = NULL;
03099 
03100         cache->flag &= ~PTCACHE_SIMULATION_VALID;
03101         cache->simframe= 0;
03102         cache->edit= NULL;
03103         cache->free_edit= NULL;
03104         cache->cached_frames= NULL;
03105 }
03106 
03107 static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointCache **ocache, int force_disk)
03108 {
03109         if(ptcaches->first) {
03110                 PointCache *cache= NULL;
03111                 link_list(fd, ptcaches);
03112                 for(cache=ptcaches->first; cache; cache=cache->next) {
03113                         direct_link_pointcache(fd, cache);
03114                         if(force_disk) {
03115                                 cache->flag |= PTCACHE_DISK_CACHE;
03116                                 cache->step = 1;
03117                         }
03118                 }
03119 
03120                 *ocache = newdataadr(fd, *ocache);
03121         }
03122         else if(*ocache) {
03123                 /* old "single" caches need to be linked too */
03124                 *ocache = newdataadr(fd, *ocache);
03125                 direct_link_pointcache(fd, *ocache);
03126                 if(force_disk) {
03127                         (*ocache)->flag |= PTCACHE_DISK_CACHE;
03128                         (*ocache)->step = 1;
03129                 }
03130 
03131                 ptcaches->first = ptcaches->last = *ocache;
03132         }
03133 }
03134 
03135 static void lib_link_partdeflect(FileData *fd, ID *id, PartDeflect *pd)
03136 {
03137         if(pd && pd->tex)
03138                 pd->tex=newlibadr_us(fd, id->lib, pd->tex);
03139 }
03140 
03141 static void lib_link_particlesettings(FileData *fd, Main *main)
03142 {
03143         ParticleSettings *part;
03144         ParticleDupliWeight *dw;
03145         MTex *mtex;
03146         int a;
03147 
03148         part= main->particle.first;
03149         while(part) {
03150                 if(part->id.flag & LIB_NEEDLINK) {
03151                         if (part->adt) lib_link_animdata(fd, &part->id, part->adt);
03152                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
03153                         
03154                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
03155                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
03156                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
03157                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
03158 
03159                         lib_link_partdeflect(fd, &part->id, part->pd);
03160                         lib_link_partdeflect(fd, &part->id, part->pd2);
03161 
03162                         if(part->effector_weights)
03163                                 part->effector_weights->group = newlibadr(fd, part->id.lib, part->effector_weights->group);
03164 
03165                         if(part->dupliweights.first && part->dup_group) {
03166                                 int index_ok = 0;
03167                                 /* check for old files without indices (all indexes 0) */
03168                                 dw = part->dupliweights.first;
03169                                 if(part->dupliweights.first == part->dupliweights.last) {
03170                                         /* special case for only one object in the group */
03171                                         index_ok = 1;
03172                                 }
03173                                 else { 
03174                                         for(; dw; dw=dw->next) {
03175                                                 if(dw->index > 0) {
03176                                                         index_ok = 1;
03177                                                         break;
03178                                                 }
03179                                         }
03180                                 }
03181 
03182                                 if(index_ok) {
03183                                         /* if we have indexes, let's use them */
03184                                         dw = part->dupliweights.first;
03185                                         for(; dw; dw=dw->next) {
03186                                                 GroupObject *go = (GroupObject *)BLI_findlink(&part->dup_group->gobject, dw->index);
03187                                                 dw->ob = go ? go->ob : NULL;
03188                                         }
03189                                 }
03190                                 else {
03191                                         /* otherwise try to get objects from own library (won't work on library linked groups) */
03192                                         for(; dw; dw=dw->next)
03193                                                 dw->ob = newlibadr(fd, part->id.lib, dw->ob);
03194                                 }
03195                         }
03196                         else {
03197                                 part->dupliweights.first = part->dupliweights.last = NULL;
03198                         }
03199 
03200                         if(part->boids) {
03201                                 BoidState *state = part->boids->states.first;
03202                                 BoidRule *rule;
03203                                 for(; state; state=state->next) {
03204                                         rule = state->rules.first;
03205                                 for(; rule; rule=rule->next)
03206                                         switch(rule->type) {
03207                                                 case eBoidRuleType_Goal:
03208                                                 case eBoidRuleType_Avoid:
03209                                                 {
03210                                                         BoidRuleGoalAvoid *brga = (BoidRuleGoalAvoid*)rule;
03211                                                         brga->ob = newlibadr(fd, part->id.lib, brga->ob);
03212                                                         break;
03213                                                 }
03214                                                 case eBoidRuleType_FollowLeader:
03215                                                 {
03216                                                         BoidRuleFollowLeader *brfl = (BoidRuleFollowLeader*)rule;
03217                                                         brfl->ob = newlibadr(fd, part->id.lib, brfl->ob);
03218                                                         break;
03219                                                 }
03220                                         }
03221                                 }
03222                         }
03223                         
03224                         for(a=0; a<MAX_MTEX; a++) {
03225                                 mtex= part->mtex[a];
03226                                 if(mtex) {
03227                                         mtex->tex = newlibadr_us(fd, part->id.lib, mtex->tex);
03228                                         mtex->object = newlibadr(fd, part->id.lib, mtex->object);
03229                                 }
03230                         }
03231 
03232                         part->id.flag -= LIB_NEEDLINK;
03233                 }
03234                 part= part->id.next;
03235         }
03236 }
03237 
03238 static void direct_link_partdeflect(PartDeflect *pd)
03239 {
03240         if(pd) pd->rng=NULL;
03241 }
03242 
03243 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
03244 {
03245         int a;
03246         part->adt= newdataadr(fd, part->adt);
03247         part->pd= newdataadr(fd, part->pd);
03248         part->pd2= newdataadr(fd, part->pd2);
03249 
03250         direct_link_animdata(fd, part->adt);
03251         direct_link_partdeflect(part->pd);
03252         direct_link_partdeflect(part->pd2);
03253 
03254         part->effector_weights = newdataadr(fd, part->effector_weights);
03255         if(!part->effector_weights)
03256                 part->effector_weights = BKE_add_effector_weights(part->eff_group);
03257 
03258         link_list(fd, &part->dupliweights);
03259 
03260         part->boids= newdataadr(fd, part->boids);
03261         part->fluid= newdataadr(fd, part->fluid);
03262 
03263         if(part->boids) {
03264                 BoidState *state;
03265                 link_list(fd, &part->boids->states);
03266                 
03267                 for(state=part->boids->states.first; state; state=state->next) {
03268                         link_list(fd, &state->rules);
03269                         link_list(fd, &state->conditions);
03270                         link_list(fd, &state->actions);
03271                 }
03272         }
03273         for(a=0; a<MAX_MTEX; a++) {
03274                 part->mtex[a]= newdataadr(fd, part->mtex[a]);
03275         }
03276 }
03277 
03278 static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
03279 {
03280         ParticleSystem *psys, *psysnext;
03281 
03282         for(psys=particles->first; psys; psys=psysnext){
03283                 psysnext= psys->next;
03284                 
03285                 psys->part = newlibadr_us(fd, id->lib, psys->part);
03286                 if(psys->part) {
03287                         ParticleTarget *pt = psys->targets.first;
03288 
03289                         for(; pt; pt=pt->next)
03290                                 pt->ob=newlibadr(fd, id->lib, pt->ob);
03291 
03292                         psys->parent= newlibadr_us(fd, id->lib, psys->parent);
03293                         psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
03294 
03295                         if(psys->clmd) {
03296                                 /* XXX - from reading existing code this seems correct but intended usage of
03297                                  * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
03298                                 psys->clmd->point_cache= psys->pointcache;
03299                                 psys->clmd->ptcaches.first= psys->clmd->ptcaches.last= NULL;
03300                                 psys->clmd->coll_parms->group= newlibadr(fd, id->lib, psys->clmd->coll_parms->group);
03301                         }
03302                 }
03303                 else {
03304                         /* particle modifier must be removed before particle system */
03305                         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
03306                         BLI_remlink(&ob->modifiers, psmd);
03307                         modifier_free((ModifierData *)psmd);
03308 
03309                         BLI_remlink(particles, psys);
03310                         MEM_freeN(psys);
03311                 }
03312         }
03313 }
03314 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
03315 {
03316         ParticleSystem *psys;
03317         ParticleData *pa;
03318         int a;
03319 
03320         for(psys=particles->first; psys; psys=psys->next) {
03321                 psys->particles=newdataadr(fd,psys->particles);
03322                 
03323                 if(psys->particles && psys->particles->hair){
03324                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
03325                                 pa->hair=newdataadr(fd,pa->hair);
03326                 }
03327                 
03328                 if(psys->particles && psys->particles->keys){
03329                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++) {
03330                                 pa->keys= NULL;
03331                                 pa->totkey= 0;
03332                         }
03333 
03334                         psys->flag &= ~PSYS_KEYED;
03335                 }
03336 
03337                 if(psys->particles && psys->particles->boid) {
03338                         pa = psys->particles;
03339                         pa->boid = newdataadr(fd, pa->boid);
03340                         for(a=1,pa++; a<psys->totpart; a++, pa++)
03341                                 pa->boid = (pa-1)->boid + 1;
03342                 }
03343                 else if(psys->particles) {
03344                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
03345                                 pa->boid = NULL;
03346                 }
03347 
03348                 psys->fluid_springs = newdataadr(fd, psys->fluid_springs);
03349 
03350                 psys->child = newdataadr(fd,psys->child);
03351                 psys->effectors = NULL;
03352 
03353                 link_list(fd, &psys->targets);
03354 
03355                 psys->edit = NULL;
03356                 psys->free_edit = NULL;
03357                 psys->pathcache = NULL;
03358                 psys->childcache = NULL;
03359                 psys->pathcachebufs.first = psys->pathcachebufs.last = NULL;
03360                 psys->childcachebufs.first = psys->childcachebufs.last = NULL;
03361                 psys->frand = NULL;
03362                 psys->pdd = NULL;
03363                 psys->renderdata = NULL;
03364                 
03365                 direct_link_pointcache_list(fd, &psys->ptcaches, &psys->pointcache, 0);
03366 
03367                 if(psys->clmd) {
03368                         psys->clmd = newdataadr(fd, psys->clmd);
03369                         psys->clmd->clothObject = NULL;
03370                         
03371                         psys->clmd->sim_parms= newdataadr(fd, psys->clmd->sim_parms);
03372                         psys->clmd->sim_parms->effector_weights = NULL;
03373                         psys->clmd->coll_parms= newdataadr(fd, psys->clmd->coll_parms);
03374                         
03375                         if(psys->clmd->sim_parms) {
03376                                 if(psys->clmd->sim_parms->presets > 10)
03377                                         psys->clmd->sim_parms->presets = 0;
03378                         }
03379 
03380                         psys->hair_in_dm = psys->hair_out_dm = NULL;
03381 
03382                         psys->clmd->point_cache = psys->pointcache;
03383                 }
03384 
03385                 psys->tree = NULL;
03386                 psys->bvhtree = NULL;
03387         }
03388         return;
03389 }
03390 
03391 /* ************ READ MESH ***************** */
03392 
03393 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
03394 {
03395         MTFace *tf= mtface;
03396         int i;
03397 
03398         for (i=0; i<totface; i++, tf++) {
03399                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
03400                 if(tf->tpage && tf->tpage->id.us==0)
03401                         tf->tpage->id.us= 1;
03402         }
03403 }
03404 
03405 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
03406 {
03407         int i;  
03408         for(i=0; i<fdata->totlayer; i++) {
03409                 CustomDataLayer *layer = &fdata->layers[i];
03410                 
03411                 if(layer->type == CD_MTFACE)
03412                         lib_link_mtface(fd, me, layer->data, totface);
03413         }
03414 
03415 }
03416 
03417 static void lib_link_mesh(FileData *fd, Main *main)
03418 {
03419         Mesh *me;
03420 
03421         me= main->mesh.first;
03422         while(me) {
03423                 if(me->id.flag & LIB_NEEDLINK) {
03424                         int i;
03425 
03426                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
03427                         of library blocks that implement this.*/
03428                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
03429                         if (me->adt) lib_link_animdata(fd, &me->id, me->adt);
03430 
03431                         /* this check added for python created meshes */
03432                         if(me->mat) {
03433                                 for(i=0; i<me->totcol; i++) {
03434                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
03435                                 }
03436                         }
03437                         else me->totcol= 0;
03438 
03439                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
03440                         me->key= newlibadr_us(fd, me->id.lib, me->key);
03441                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
03442 
03443                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
03444                         if(me->mr && me->mr->levels.first)
03445                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
03446                                                            ((MultiresLevel*)me->mr->levels.first)->totface);
03447 
03448                         me->id.flag -= LIB_NEEDLINK;
03449                 }
03450                 me= me->id.next;
03451         }
03452 }
03453 
03454 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
03455 {
03456         int i;
03457 
03458         if (mdverts == NULL) {
03459                 return;
03460         }
03461 
03462         for (i= count; i > 0; i--, mdverts++) {
03463                 if(mdverts->dw) {
03464                         mdverts->dw= newdataadr(fd, mdverts->dw);
03465                 }
03466                 if (mdverts->dw == NULL) {
03467                         mdverts->totweight= 0;
03468                 }
03469         }
03470 }
03471 
03472 static void direct_link_mdisps(FileData *fd, int count, MDisps *mdisps, int external)
03473 {
03474         if(mdisps) {
03475                 int i;
03476 
03477                 for(i = 0; i < count; ++i) {
03478                         mdisps[i].disps = newdataadr(fd, mdisps[i].disps);
03479 
03480                         if( (fd->flags & FD_FLAGS_SWITCH_ENDIAN) && (mdisps[i].disps) ) {
03481                                 /* DNA_struct_switch_endian doesn't do endian swap for (*disps)[] */
03482                                 /* this does swap for data written at write_mdisps() - readfile.c */
03483                                 int x;
03484                                 float *tmpdisps= *mdisps[i].disps;
03485                                 for(x=0;x<mdisps[i].totdisp*3;x++) {
03486                                         SWITCH_INT(*tmpdisps);
03487                                         tmpdisps++;
03488                                 }
03489                         }
03490                         if(!external && !mdisps[i].disps)
03491                                 mdisps[i].totdisp = 0;
03492                 }
03493         }
03494 }
03495 
03496 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
03497 {
03498         int i = 0;
03499 
03500         data->layers= newdataadr(fd, data->layers);
03501         data->external= newdataadr(fd, data->external);
03502 
03503         while (i < data->totlayer) {
03504                 CustomDataLayer *layer = &data->layers[i];
03505 
03506                 if(layer->flag & CD_FLAG_EXTERNAL)
03507                         layer->flag &= ~CD_FLAG_IN_MEMORY;
03508 
03509                 if (CustomData_verify_versions(data, i)) {
03510                         layer->data = newdataadr(fd, layer->data);
03511                         if(layer->type == CD_MDISPS)
03512                                 direct_link_mdisps(fd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
03513                         i++;
03514                 }
03515         }
03516 }
03517 
03518 static void direct_link_mesh(FileData *fd, Mesh *mesh)
03519 {
03520         mesh->mat= newdataadr(fd, mesh->mat);
03521         test_pointer_array(fd, (void **)&mesh->mat);
03522 
03523         mesh->mvert= newdataadr(fd, mesh->mvert);
03524         mesh->medge= newdataadr(fd, mesh->medge);
03525         mesh->mface= newdataadr(fd, mesh->mface);
03526         mesh->tface= newdataadr(fd, mesh->tface);
03527         mesh->mtface= newdataadr(fd, mesh->mtface);
03528         mesh->mcol= newdataadr(fd, mesh->mcol);
03529         mesh->msticky= newdataadr(fd, mesh->msticky);
03530         mesh->dvert= newdataadr(fd, mesh->dvert);
03531         
03532         /* animdata */
03533         mesh->adt= newdataadr(fd, mesh->adt);
03534         direct_link_animdata(fd, mesh->adt);
03535 
03536         /* Partial-mesh visibility (do this before using totvert, totface, or totedge!) */
03537         mesh->pv= newdataadr(fd, mesh->pv);
03538         if(mesh->pv) {
03539                 mesh->pv->vert_map= newdataadr(fd, mesh->pv->vert_map);
03540                 mesh->pv->edge_map= newdataadr(fd, mesh->pv->edge_map);
03541                 mesh->pv->old_faces= newdataadr(fd, mesh->pv->old_faces);
03542                 mesh->pv->old_edges= newdataadr(fd, mesh->pv->old_edges);
03543         }
03544 
03545         /* normally direct_link_dverts should be called in direct_link_customdata,
03546            but for backwards compat in do_versions to work we do it here */
03547         direct_link_dverts(fd, mesh->pv ? mesh->pv->totvert : mesh->totvert, mesh->dvert);
03548 
03549         direct_link_customdata(fd, &mesh->vdata, mesh->pv ? mesh->pv->totvert : mesh->totvert);
03550         direct_link_customdata(fd, &mesh->edata, mesh->pv ? mesh->pv->totedge : mesh->totedge);
03551         direct_link_customdata(fd, &mesh->fdata, mesh->pv ? mesh->pv->totface : mesh->totface);
03552 
03553         mesh->bb= NULL;
03554         mesh->mselect = NULL;
03555         mesh->edit_mesh= NULL;
03556         
03557         /* Multires data */
03558         mesh->mr= newdataadr(fd, mesh->mr);
03559         if(mesh->mr) {
03560                 MultiresLevel *lvl;
03561                 
03562                 link_list(fd, &mesh->mr->levels);
03563                 lvl= mesh->mr->levels.first;
03564                 
03565                 direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
03566                 direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
03567                 direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
03568                 
03569                 mesh->mr->edge_flags= newdataadr(fd, mesh->mr->edge_flags);
03570                 mesh->mr->edge_creases= newdataadr(fd, mesh->mr->edge_creases);
03571 
03572                 mesh->mr->verts = newdataadr(fd, mesh->mr->verts);
03573                 
03574                 /* If mesh has the same number of vertices as the
03575                    highest multires level, load the current mesh verts
03576                    into multires and discard the old data. Needed
03577                    because some saved files either do not have a verts
03578                    array, or the verts array contains out-of-date
03579                    data. */
03580                 if(mesh->totvert == ((MultiresLevel*)mesh->mr->levels.last)->totvert) {
03581                         if(mesh->mr->verts)
03582                                 MEM_freeN(mesh->mr->verts);
03583                         mesh->mr->verts = MEM_dupallocN(mesh->mvert);
03584                 }
03585                         
03586                 for(; lvl; lvl= lvl->next) {
03587                         lvl->verts= newdataadr(fd, lvl->verts);
03588                         lvl->faces= newdataadr(fd, lvl->faces);
03589                         lvl->edges= newdataadr(fd, lvl->edges);
03590                         lvl->colfaces= newdataadr(fd, lvl->colfaces);
03591                 }
03592         }
03593 
03594         /* if multires is present but has no valid vertex data,
03595            there's no way to recover it; silently remove multires */
03596         if(mesh->mr && !mesh->mr->verts) {
03597                 multires_free(mesh->mr);
03598                 mesh->mr = NULL;
03599         }
03600         
03601         if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
03602                 TFace *tf= mesh->tface;
03603                 unsigned int i;
03604 
03605                 for (i=0; i< (mesh->pv ? mesh->pv->totface : mesh->totface); i++, tf++) {
03606                         SWITCH_INT(tf->col[0]);
03607                         SWITCH_INT(tf->col[1]);
03608                         SWITCH_INT(tf->col[2]);
03609                         SWITCH_INT(tf->col[3]);
03610                 }
03611         }
03612 }
03613 
03614 /* ************ READ LATTICE ***************** */
03615 
03616 static void lib_link_latt(FileData *fd, Main *main)
03617 {
03618         Lattice *lt;
03619         
03620         lt= main->latt.first;
03621         while(lt) {
03622                 if(lt->id.flag & LIB_NEEDLINK) {
03623                         if(lt->adt) lib_link_animdata(fd, &lt->id, lt->adt);
03624                         
03625                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo); // XXX depreceated - old animation system
03626                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
03627                         
03628                         lt->id.flag -= LIB_NEEDLINK;
03629                 }
03630                 lt= lt->id.next;
03631         }
03632 }
03633 
03634 static void direct_link_latt(FileData *fd, Lattice *lt)
03635 {
03636         lt->def= newdataadr(fd, lt->def);
03637         
03638         lt->dvert= newdataadr(fd, lt->dvert);
03639         direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
03640         
03641         lt->editlatt= NULL;
03642         
03643         lt->adt = newdataadr(fd, lt->adt);
03644         direct_link_animdata(fd, lt->adt);
03645 }
03646 
03647 
03648 /* ************ READ OBJECT ***************** */
03649 
03650 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob,
03651                                                                                           ID **idpoin)
03652 {
03653         FileData *fd = userData;
03654 
03655         *idpoin = newlibadr(fd, ob->id.lib, *idpoin);
03656         /* hardcoded bad exception; non-object modifier data gets user count (texture, displace) */
03657         if(*idpoin && GS((*idpoin)->name)!=ID_OB)
03658                 (*idpoin)->us++;
03659 }
03660 static void lib_link_modifiers(FileData *fd, Object *ob)
03661 {
03662         modifiers_foreachIDLink(ob, lib_link_modifiers__linkModifiers, fd);
03663 }
03664 
03665 static void lib_link_object(FileData *fd, Main *main)
03666 {
03667         Object *ob;
03668         PartEff *paf;
03669         bSensor *sens;
03670         bController *cont;
03671         bActuator *act;
03672         void *poin;
03673         int warn=0, a;
03674 
03675         ob= main->object.first;
03676         while(ob) {
03677                 if(ob->id.flag & LIB_NEEDLINK) {
03678                         if (ob->id.properties) IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
03679                         if (ob->adt) lib_link_animdata(fd, &ob->id, ob->adt);
03680                         
03681 // XXX depreceated - old animation system <<<                   
03682                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
03683                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
03684 // >>> XXX depreceated - old animation system
03685 
03686                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
03687                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
03688                         ob->poselib= newlibadr_us(fd, ob->id.lib, ob->poselib);
03689                         ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
03690                         
03691                         ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
03692                         if(ob->proxy) {
03693                                 /* paranoia check, actually a proxy_from pointer should never be written... */
03694                                 if(ob->proxy->id.lib==NULL) {
03695                                         ob->proxy->proxy_from= NULL;
03696                                         ob->proxy= NULL;
03697                                         
03698                                         if (ob->id.lib)
03699                                                 printf("Proxy lost from  object %s lib %s\n", ob->id.name+2, ob->id.lib->name);
03700                                         else
03701                                                 printf("Proxy lost from  object %s lib <NONE>\n", ob->id.name+2);
03702                                 }
03703                                 else {
03704                                         /* this triggers object_update to always use a copy */
03705                                         ob->proxy->proxy_from= ob;
03706                                         /* force proxy updates after load/undo, a bit weak */
03707                                         ob->recalc= ob->proxy->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
03708                                 }
03709                         }
03710                         ob->proxy_group= newlibadr(fd, ob->id.lib, ob->proxy_group);
03711                         
03712                         poin= ob->data;
03713                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
03714 
03715                         if(ob->data==NULL && poin!=NULL) {
03716                                 if(ob->id.lib)
03717                                         printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
03718                                 else
03719                                         printf("Object %s lost data.\n", ob->id.name+2);
03720 
03721                                 ob->type= OB_EMPTY;
03722                                 warn= 1;
03723 
03724                                 if(ob->pose) {
03725                                         free_pose(ob->pose);
03726                                         ob->pose= NULL;
03727                                         ob->mode &= ~OB_MODE_POSE;
03728                                 }
03729                         }
03730                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
03731                         
03732                         /* When the object is local and the data is library its possible
03733                          * the material list size gets out of sync. [#22663] */
03734                         if(ob->data && ob->id.lib != ((ID *)ob->data)->lib) {
03735                                 short *totcol_data= give_totcolp(ob);
03736                                 /* Only expand so as not to loose any object materials that might be set. */
03737                                 if(totcol_data && *totcol_data > ob->totcol) {
03738                                         /* printf("'%s' %d -> %d\n", ob->id.name, ob->totcol, *totcol_data); */
03739                                         resize_object_material(ob, *totcol_data);
03740                                 }
03741                         }
03742 
03743                         ob->gpd= newlibadr_us(fd, ob->id.lib, ob->gpd);
03744                         ob->duplilist= NULL;
03745 
03746                         ob->id.flag -= LIB_NEEDLINK;
03747                         /* if id.us==0 a new base will be created later on */
03748                         
03749                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
03750                         lib_link_pose(fd, ob, ob->pose);
03751                         lib_link_constraints(fd, &ob->id, &ob->constraints);
03752                         
03753 // XXX depreceated - old animation system <<<   
03754                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
03755                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
03756 // >>> XXX depreceated - old animation system
03757 
03758                         for(paf= ob->effect.first; paf; paf= paf->next) {
03759                                 if(paf->type==EFF_PARTICLE) {
03760                                         paf->group= newlibadr_us(fd, ob->id.lib, paf->group);
03761                                 }
03762                         }                               
03763 
03764                         sens= ob->sensors.first;
03765                         while(sens) {
03766                                 for(a=0; a<sens->totlinks; a++)
03767                                         sens->links[a]= newglobadr(fd, sens->links[a]);
03768 
03769                                 if(sens->type==SENS_TOUCH) {
03770                                         bTouchSensor *ts= sens->data;
03771                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
03772                                 }
03773                                 else if(sens->type==SENS_MESSAGE) {
03774                                         bMessageSensor *ms= sens->data;
03775                                         ms->fromObject=
03776                                                 newlibadr(fd, ob->id.lib, ms->fromObject);
03777                                 }
03778                                 sens= sens->next;
03779                         }
03780 
03781                         cont= ob->controllers.first;
03782                         while(cont) {
03783                                 for(a=0; a<cont->totlinks; a++)
03784                                         cont->links[a]= newglobadr(fd, cont->links[a]);
03785 
03786                                 if(cont->type==CONT_PYTHON) {
03787                                         bPythonCont *pc= cont->data;
03788                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
03789                                 }
03790                                 cont->slinks= NULL;
03791                                 cont->totslinks= 0;
03792 
03793                                 cont= cont->next;
03794                         }
03795 
03796                         act= ob->actuators.first;
03797                         while(act) {
03798                                 if(act->type==ACT_SOUND) {
03799                                         bSoundActuator *sa= act->data;
03800                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
03801                                 }
03802                                 else if(act->type==ACT_GAME) {
03803                                         /* bGameActuator *ga= act->data; */
03804                                 }
03805                                 else if(act->type==ACT_CAMERA) {
03806                                         bCameraActuator *ca= act->data;
03807                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
03808                                 }
03809                                         /* leave this one, it's obsolete but necessary to read for conversion */
03810                                 else if(act->type==ACT_ADD_OBJECT) {
03811                                         bAddObjectActuator *eoa= act->data;
03812                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
03813                                 }
03814                                 else if(act->type==ACT_OBJECT) {
03815                                         bObjectActuator *oa= act->data;
03816                                         if(oa==NULL) {
03817                                                 init_actuator(act);
03818                                         }
03819                                         else {
03820                                                 oa->reference= newlibadr(fd, ob->id.lib, oa->reference);
03821                                         }
03822                                 }
03823                                 else if(act->type==ACT_EDIT_OBJECT) {
03824                                         bEditObjectActuator *eoa= act->data;
03825                                         if(eoa==NULL) {
03826                                                 init_actuator(act);
03827                                         }
03828                                         else {
03829                                                 eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
03830                                                 eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
03831                                         }
03832                                 }
03833                                 else if(act->type==ACT_SCENE) {
03834                                         bSceneActuator *sa= act->data;
03835                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
03836                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
03837                                 }
03838                                 else if(act->type==ACT_ACTION) {
03839                                         bActionActuator *aa= act->data;
03840                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
03841                                 }
03842                                 else if(act->type==ACT_SHAPEACTION) {
03843                                         bActionActuator *aa= act->data;
03844                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
03845                                 }
03846                                 else if(act->type==ACT_PROPERTY) {
03847                                         bPropertyActuator *pa= act->data;
03848                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
03849                                 }
03850                                 else if(act->type==ACT_MESSAGE) {
03851                                         bMessageActuator *ma= act->data;
03852                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
03853                                 }
03854                                 else if(act->type==ACT_2DFILTER){
03855                                         bTwoDFilterActuator *_2dfa = act->data; 
03856                                         _2dfa->text= newlibadr(fd, ob->id.lib, _2dfa->text);
03857                                 }
03858                                 else if(act->type==ACT_PARENT) {
03859                                         bParentActuator *parenta = act->data; 
03860                                         parenta->ob = newlibadr(fd, ob->id.lib, parenta->ob);
03861                                 }
03862                                 else if(act->type==ACT_STATE) {
03863                                         /* bStateActuator *statea = act->data; */
03864                                 }
03865                                 else if(act->type==ACT_ARMATURE) {
03866                                         bArmatureActuator *arma= act->data;
03867                                         arma->target= newlibadr(fd, ob->id.lib, arma->target);
03868                                         arma->subtarget= newlibadr(fd, ob->id.lib, arma->subtarget);
03869                                 }
03870                                 act= act->next;
03871                         }
03872                         
03873                         {
03874                                 FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
03875                                 
03876                                 if(fluidmd && fluidmd->fss) 
03877                                         fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, fluidmd->fss->ipo);
03878                         }
03879 
03880                         {
03881                                 SmokeModifierData *smd = (SmokeModifierData *)modifiers_findByType(ob, eModifierType_Smoke);
03882                                 
03883                                 if(smd && smd->type == MOD_SMOKE_TYPE_DOMAIN && smd->domain) 
03884                                 {
03885                                         smd->domain->flags |= MOD_SMOKE_FILE_LOAD; /* flag for refreshing the simulation after loading */
03886                                 }
03887                         }
03888 
03889                         /* texture field */
03890                         if(ob->pd)
03891                                 lib_link_partdeflect(fd, &ob->id, ob->pd);
03892 
03893                         if(ob->soft)
03894                                 ob->soft->effector_weights->group = newlibadr(fd, ob->id.lib, ob->soft->effector_weights->group);
03895 
03896                         lib_link_particlesystems(fd, ob, &ob->id, &ob->particlesystem);
03897                         lib_link_modifiers(fd, ob);
03898                 }
03899                 ob= ob->id.next;
03900         }
03901 
03902         if(warn)
03903                 BKE_report(fd->reports, RPT_WARNING, "Warning in console");
03904 }
03905 
03906 
03907 static void direct_link_pose(FileData *fd, bPose *pose)
03908 {
03909         bPoseChannel *pchan;
03910 
03911         if (!pose)
03912                 return;
03913 
03914         link_list(fd, &pose->chanbase);
03915         link_list(fd, &pose->agroups);
03916 
03917         pose->chanhash= NULL;
03918 
03919         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
03920                 pchan->bone= NULL;
03921                 pchan->parent= newdataadr(fd, pchan->parent);
03922                 pchan->child= newdataadr(fd, pchan->child);
03923                 pchan->custom_tx= newdataadr(fd, pchan->custom_tx);
03924                 
03925                 direct_link_constraints(fd, &pchan->constraints);
03926                 
03927                 pchan->prop = newdataadr(fd, pchan->prop);
03928                 if (pchan->prop)
03929                         IDP_DirectLinkProperty(pchan->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
03930                 
03931                 pchan->mpath= newdataadr(fd, pchan->mpath);
03932                 if (pchan->mpath)
03933                         direct_link_motionpath(fd, pchan->mpath);
03934                 
03935                 pchan->iktree.first= pchan->iktree.last= NULL;
03936                 pchan->path= NULL;
03937                 
03938                 /* incase this value changes in future, clamp else we get undefined behavior */
03939                 CLAMP(pchan->rotmode, ROT_MODE_MIN, ROT_MODE_MAX);
03940         }
03941         pose->ikdata = NULL;
03942         if (pose->ikparam != NULL) {
03943                 pose->ikparam= newdataadr(fd, pose->ikparam);
03944         }
03945 }
03946 
03947 static void direct_link_modifiers(FileData *fd, ListBase *lb)
03948 {
03949         ModifierData *md;
03950 
03951         link_list(fd, lb);
03952 
03953         for (md=lb->first; md; md=md->next) {
03954                 md->error = NULL;
03955                 md->scene = NULL;
03956                 
03957                 /* if modifiers disappear, or for upward compatibility */
03958                 if(NULL==modifierType_getInfo(md->type))
03959                         md->type= eModifierType_None;
03960                         
03961                 if (md->type==eModifierType_Subsurf) {
03962                         SubsurfModifierData *smd = (SubsurfModifierData*) md;
03963 
03964                         smd->emCache = smd->mCache = NULL;
03965                 }
03966                 else if (md->type==eModifierType_Armature) {
03967                         ArmatureModifierData *amd = (ArmatureModifierData*) md;
03968                         
03969                         amd->prevCos= NULL;
03970                 }
03971                 else if (md->type==eModifierType_Cloth) {
03972                         ClothModifierData *clmd = (ClothModifierData*) md;
03973                         
03974                         clmd->clothObject = NULL;
03975                         
03976                         clmd->sim_parms= newdataadr(fd, clmd->sim_parms);
03977                         clmd->coll_parms= newdataadr(fd, clmd->coll_parms);
03978 
03979                         direct_link_pointcache_list(fd, &clmd->ptcaches, &clmd->point_cache, 0);
03980                         
03981                         if(clmd->sim_parms) {
03982                                 if(clmd->sim_parms->presets > 10)
03983                                         clmd->sim_parms->presets = 0;
03984 
03985                                 clmd->sim_parms->reset = 0;
03986 
03987                                 clmd->sim_parms->effector_weights = newdataadr(fd, clmd->sim_parms->effector_weights);
03988 
03989                                 if(!clmd->sim_parms->effector_weights) {
03990                                         clmd->sim_parms->effector_weights = BKE_add_effector_weights(NULL);
03991                                 }
03992                         }
03993                 }
03994                 else if (md->type==eModifierType_Fluidsim) {
03995                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
03996                         
03997                         fluidmd->fss= newdataadr(fd, fluidmd->fss);
03998                         fluidmd->fss->fmd= fluidmd;
03999                         fluidmd->fss->meshVelocities = NULL;
04000                 }
04001                 else if (md->type==eModifierType_Smoke) {
04002                         SmokeModifierData *smd = (SmokeModifierData*) md;
04003 
04004                         if(smd->type==MOD_SMOKE_TYPE_DOMAIN)
04005                         {
04006                                 smd->flow = NULL;
04007                                 smd->coll = NULL;
04008                                 smd->domain = newdataadr(fd, smd->domain);
04009                                 smd->domain->smd = smd;
04010 
04011                                 smd->domain->fluid = NULL;
04012                                 smd->domain->wt = NULL;
04013                                 smd->domain->shadow = NULL;
04014                                 smd->domain->tex = NULL;
04015                                 smd->domain->tex_shadow = NULL;
04016                                 smd->domain->tex_wt = NULL;
04017 
04018                                 smd->domain->effector_weights = newdataadr(fd, smd->domain->effector_weights);
04019                                 if(!smd->domain->effector_weights)
04020                                         smd->domain->effector_weights = BKE_add_effector_weights(NULL);
04021 
04022                                 direct_link_pointcache_list(fd, &(smd->domain->ptcaches[0]), &(smd->domain->point_cache[0]), 1);
04023 
04024                                 /* Smoke uses only one cache from now on, so store pointer convert */
04025                                 if(smd->domain->ptcaches[1].first || smd->domain->point_cache[1]) {
04026                                         if(smd->domain->point_cache[1]) {
04027                                                 PointCache *cache = newdataadr(fd, smd->domain->point_cache[1]);
04028                                                 if(cache->flag & PTCACHE_FAKE_SMOKE)
04029                                                         ; /* Smoke was already saved in "new format" and this cache is a fake one. */
04030                                                 else
04031                                                         printf("High resolution smoke cache not available due to pointcache update. Please reset the simulation.\n");
04032                                                 BKE_ptcache_free(cache);
04033                                         }
04034                                         smd->domain->ptcaches[1].first = NULL;
04035                                         smd->domain->ptcaches[1].last = NULL;
04036                                         smd->domain->point_cache[1] = NULL;
04037                                 }
04038                         }
04039                         else if(smd->type==MOD_SMOKE_TYPE_FLOW)
04040                         {
04041                                 smd->domain = NULL;
04042                                 smd->coll = NULL;
04043                                 smd->flow = newdataadr(fd, smd->flow);
04044                                 smd->flow->smd = smd;
04045                                 smd->flow->psys = newdataadr(fd, smd->flow->psys);
04046                         }
04047                         else if(smd->type==MOD_SMOKE_TYPE_COLL)
04048                         {
04049                                 smd->flow = NULL;
04050                                 smd->domain = NULL;
04051                                 smd->coll = newdataadr(fd, smd->coll);
04052                                 if(smd->coll)
04053                                 {
04054                                         smd->coll->points = NULL;
04055                                         smd->coll->numpoints = 0;
04056                                 }
04057                                 else
04058                                         smd->type = 0;
04059 
04060                         }
04061                 }
04062                 else if (md->type==eModifierType_Collision) {
04063                         
04064                         CollisionModifierData *collmd = (CollisionModifierData*) md;
04065                         /*
04066                         // TODO: CollisionModifier should use pointcache 
04067                         // + have proper reset events before enabling this
04068                         collmd->x = newdataadr(fd, collmd->x);
04069                         collmd->xnew = newdataadr(fd, collmd->xnew);
04070                         collmd->mfaces = newdataadr(fd, collmd->mfaces);
04071                         
04072                         collmd->current_x = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_x");
04073                         collmd->current_xnew = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_xnew");
04074                         collmd->current_v = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_v");
04075                         */
04076                         
04077                         collmd->x = NULL;
04078                         collmd->xnew = NULL;
04079                         collmd->current_x = NULL;
04080                         collmd->current_xnew = NULL;
04081                         collmd->current_v = NULL;
04082                         collmd->time_x = collmd->time_xnew = -1000;
04083                         collmd->numverts = 0;
04084                         collmd->bvhtree = NULL;
04085                         collmd->mfaces = NULL;
04086                         
04087                 }
04088                 else if (md->type==eModifierType_Surface) {
04089                         SurfaceModifierData *surmd = (SurfaceModifierData*) md;
04090 
04091                         surmd->dm = NULL;
04092                         surmd->bvhtree = NULL;
04093                         surmd->x = NULL;
04094                         surmd->v = NULL;
04095                         surmd->numverts = 0;
04096                 }
04097                 else if (md->type==eModifierType_Hook) {
04098                         HookModifierData *hmd = (HookModifierData*) md;
04099 
04100                         hmd->indexar= newdataadr(fd, hmd->indexar);
04101                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
04102                                 int a;
04103                                 for(a=0; a<hmd->totindex; a++) {
04104                                         SWITCH_INT(hmd->indexar[a]);
04105                                 }
04106                         }
04107                 } else if (md->type==eModifierType_ParticleSystem) {
04108                         ParticleSystemModifierData *psmd = (ParticleSystemModifierData*) md;
04109 
04110                         psmd->dm= NULL;
04111                         psmd->psys= newdataadr(fd, psmd->psys);
04112                         psmd->flag &= ~eParticleSystemFlag_psys_updated;
04113                         psmd->flag |= eParticleSystemFlag_file_loaded;
04114                 } else if (md->type==eModifierType_Explode) {
04115                         ExplodeModifierData *psmd = (ExplodeModifierData*) md;
04116 
04117                         psmd->facepa=NULL;
04118                 }
04119                 else if (md->type==eModifierType_MeshDeform) {
04120                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
04121 
04122                         mmd->bindinfluences= newdataadr(fd, mmd->bindinfluences);
04123                         mmd->bindoffsets= newdataadr(fd, mmd->bindoffsets);
04124                         mmd->bindcagecos= newdataadr(fd, mmd->bindcagecos);
04125                         mmd->dyngrid= newdataadr(fd, mmd->dyngrid);
04126                         mmd->dyninfluences= newdataadr(fd, mmd->dyninfluences);
04127                         mmd->dynverts= newdataadr(fd, mmd->dynverts);
04128 
04129                         mmd->bindweights= newdataadr(fd, mmd->bindweights);
04130                         mmd->bindcos= newdataadr(fd, mmd->bindcos);
04131 
04132                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
04133                                 int a;
04134 
04135                                 if(mmd->bindoffsets)
04136                                         for(a=0; a<mmd->totvert+1; a++)
04137                                                 SWITCH_INT(mmd->bindoffsets[a])
04138                                 if(mmd->bindcagecos)
04139                                         for(a=0; a<mmd->totcagevert*3; a++)
04140                                                 SWITCH_INT(mmd->bindcagecos[a])
04141                                 if(mmd->dynverts)
04142                                         for(a=0; a<mmd->totvert; a++)
04143                                                 SWITCH_INT(mmd->dynverts[a])
04144 
04145                                 if(mmd->bindweights)
04146                                         for(a=0; a<mmd->totcagevert*mmd->totvert; a++)
04147                                                 SWITCH_INT(mmd->bindweights[a])
04148                                 if(mmd->bindcos)
04149                                         for(a=0; a<mmd->totcagevert*3; a++)
04150                                                 SWITCH_INT(mmd->bindcos[a])
04151                         }
04152                 }
04153                 else if (md->type==eModifierType_Warp) {
04154                         WarpModifierData *tmd = (WarpModifierData *) md;
04155 
04156                         tmd->curfalloff= newdataadr(fd, tmd->curfalloff);
04157                         if(tmd->curfalloff)
04158                                 direct_link_curvemapping(fd, tmd->curfalloff);
04159                 }
04160         }
04161 }
04162 
04163 static void direct_link_object(FileData *fd, Object *ob)
04164 {
04165         PartEff *paf;
04166         bProperty *prop;
04167         bSensor *sens;
04168         bController *cont;
04169         bActuator *act;
04170         
04171         /* weak weak... this was only meant as draw flag, now is used in give_base_to_objects too */
04172         ob->flag &= ~OB_FROMGROUP;
04173 
04174         /* loading saved files with editmode enabled works, but for undo we like
04175            to stay in object mode during undo presses so keep editmode disabled */
04176         if(fd->memfile)
04177                 ob->mode &= ~(OB_MODE_EDIT|OB_MODE_PARTICLE_EDIT);
04178         
04179         ob->disp.first=ob->disp.last= NULL;
04180         
04181         ob->adt= newdataadr(fd, ob->adt);
04182         direct_link_animdata(fd, ob->adt);
04183         
04184         ob->pose= newdataadr(fd, ob->pose);
04185         direct_link_pose(fd, ob->pose);
04186         
04187         ob->mpath= newdataadr(fd, ob->mpath);
04188         if (ob->mpath)
04189                 direct_link_motionpath(fd, ob->mpath);
04190 
04191         link_list(fd, &ob->defbase);
04192 // XXX depreceated - old animation system <<<
04193         direct_link_nlastrips(fd, &ob->nlastrips);
04194         link_list(fd, &ob->constraintChannels);
04195 // >>> XXX depreceated - old animation system 
04196 
04197         ob->mat= newdataadr(fd, ob->mat);
04198         test_pointer_array(fd, (void **)&ob->mat);
04199         ob->matbits= newdataadr(fd, ob->matbits);
04200         
04201         /* do it here, below old data gets converted */
04202         direct_link_modifiers(fd, &ob->modifiers);
04203         
04204         link_list(fd, &ob->effect);
04205         paf= ob->effect.first;
04206         while(paf) {
04207                 if(paf->type==EFF_PARTICLE) {
04208                         paf->keys= NULL;
04209                 }
04210                 if(paf->type==EFF_WAVE) {
04211                         WaveEff *wav = (WaveEff*) paf;
04212                         PartEff *next = paf->next;
04213                         WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave);
04214 
04215                         wmd->damp = wav->damp;
04216                         wmd->flag = wav->flag;
04217                         wmd->height = wav->height;
04218                         wmd->lifetime = wav->lifetime;
04219                         wmd->narrow = wav->narrow;
04220                         wmd->speed = wav->speed;
04221                         wmd->startx = wav->startx;
04222                         wmd->starty = wav->startx;
04223                         wmd->timeoffs = wav->timeoffs;
04224                         wmd->width = wav->width;
04225 
04226                         BLI_addtail(&ob->modifiers, wmd);
04227 
04228                         BLI_remlink(&ob->effect, paf);
04229                         MEM_freeN(paf);
04230 
04231                         paf = next;
04232                         continue;
04233                 }
04234                 if(paf->type==EFF_BUILD) {
04235                         BuildEff *baf = (BuildEff*) paf;
04236                         PartEff *next = paf->next;
04237                         BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build);
04238 
04239                         bmd->start = baf->sfra;
04240                         bmd->length = baf->len;
04241                         bmd->randomize = 0;
04242                         bmd->seed = 1;
04243 
04244                         BLI_addtail(&ob->modifiers, bmd);
04245 
04246                         BLI_remlink(&ob->effect, paf);
04247                         MEM_freeN(paf);
04248 
04249                         paf = next;
04250                         continue;
04251                 }
04252                 paf= paf->next;
04253         }
04254 
04255         ob->pd= newdataadr(fd, ob->pd);
04256         direct_link_partdeflect(ob->pd);
04257         ob->soft= newdataadr(fd, ob->soft);
04258         if(ob->soft) {
04259                 SoftBody *sb= ob->soft;         
04260                 
04261                 sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
04262                 sb->bspring= NULL;
04263                 sb->scratch= NULL;
04264                 /* although not used anymore */
04265                 /* still have to be loaded to be compatible with old files */
04266                 sb->keys= newdataadr(fd, sb->keys);
04267                 test_pointer_array(fd, (void **)&sb->keys);
04268                 if(sb->keys) {
04269                         int a;
04270                         for(a=0; a<sb->totkey; a++) {
04271                                 sb->keys[a]= newdataadr(fd, sb->keys[a]);
04272                         }
04273                 }
04274 
04275                 sb->effector_weights = newdataadr(fd, sb->effector_weights);
04276                 if(!sb->effector_weights)
04277                         sb->effector_weights = BKE_add_effector_weights(NULL);
04278 
04279                 direct_link_pointcache_list(fd, &sb->ptcaches, &sb->pointcache, 0);
04280         }
04281         ob->bsoft= newdataadr(fd, ob->bsoft);
04282         ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
04283 
04284         link_list(fd, &ob->particlesystem);
04285         direct_link_particlesystems(fd,&ob->particlesystem);
04286         
04287         link_list(fd, &ob->prop);
04288         prop= ob->prop.first;
04289         while(prop) {
04290                 prop->poin= newdataadr(fd, prop->poin);
04291                 if(prop->poin==NULL) prop->poin= &prop->data;
04292                 prop= prop->next;
04293         }
04294 
04295         link_list(fd, &ob->sensors);
04296         sens= ob->sensors.first;
04297         while(sens) {
04298                 sens->data= newdataadr(fd, sens->data);
04299                 sens->links= newdataadr(fd, sens->links);
04300                 test_pointer_array(fd, (void **)&sens->links);
04301                 sens= sens->next;
04302         }
04303 
04304         direct_link_constraints(fd, &ob->constraints);
04305 
04306         link_glob_list(fd, &ob->controllers);
04307         if (ob->init_state) {
04308                 /* if a known first state is specified, set it so that the game will start ok */
04309                 ob->state = ob->init_state;
04310         } else if (!ob->state) {
04311                 ob->state = 1;
04312         }
04313         cont= ob->controllers.first;
04314         while(cont) {
04315                 cont->data= newdataadr(fd, cont->data);
04316                 cont->links= newdataadr(fd, cont->links);
04317                 test_pointer_array(fd, (void **)&cont->links);
04318                 if (cont->state_mask == 0)
04319                         cont->state_mask = 1;
04320                 cont= cont->next;
04321         }
04322 
04323         link_glob_list(fd, &ob->actuators);
04324         act= ob->actuators.first;
04325         while(act) {
04326                 act->data= newdataadr(fd, act->data);
04327                 act= act->next;
04328         }
04329 
04330         link_list(fd, &ob->hooks);
04331         while (ob->hooks.first) {
04332                 ObHook *hook = ob->hooks.first;
04333                 HookModifierData *hmd = (HookModifierData*) modifier_new(eModifierType_Hook);
04334 
04335                 hook->indexar= newdataadr(fd, hook->indexar);
04336                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
04337                         int a;
04338                         for(a=0; a<hook->totindex; a++) {
04339                                 SWITCH_INT(hook->indexar[a]);
04340                         }
04341                 }
04342 
04343                         /* Do conversion here because if we have loaded
04344                          * a hook we need to make sure it gets converted
04345                          * and free'd, regardless of version.
04346                          */
04347                 VECCOPY(hmd->cent, hook->cent);
04348                 hmd->falloff = hook->falloff;
04349                 hmd->force = hook->force;
04350                 hmd->indexar = hook->indexar;
04351                 hmd->object = hook->parent;
04352                 memcpy(hmd->parentinv, hook->parentinv, sizeof(hmd->parentinv));
04353                 hmd->totindex = hook->totindex;
04354 
04355                 BLI_addhead(&ob->modifiers, hmd);
04356                 BLI_remlink(&ob->hooks, hook);
04357                 
04358                 modifier_unique_name(&ob->modifiers, (ModifierData*)hmd);
04359 
04360                 MEM_freeN(hook);
04361         }
04362         
04363         ob->customdata_mask= 0;
04364         ob->bb= NULL;
04365         ob->derivedDeform= NULL;
04366         ob->derivedFinal= NULL;
04367         ob->gpulamp.first= ob->gpulamp.last= NULL;
04368         link_list(fd, &ob->pc_ids);
04369 
04370         /* incase this value changes in future, clamp else we get undefined behavior */
04371         CLAMP(ob->rotmode, ROT_MODE_MIN, ROT_MODE_MAX);
04372 
04373         if(ob->sculpt) {
04374                 ob->sculpt= MEM_callocN(sizeof(SculptSession), "reload sculpt session");
04375         }
04376 }
04377 
04378 /* ************ READ SCENE ***************** */
04379 
04380 /* patch for missing scene IDs, can't be in do-versions */
04381 static void composite_patch(bNodeTree *ntree, Scene *scene)
04382 {
04383         bNode *node;
04384         
04385         for(node= ntree->nodes.first; node; node= node->next)
04386                 if(node->id==NULL && ELEM4(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE, CMP_NODE_DEFOCUS, CMP_NODE_OUTPUT_FILE))
04387                         node->id= &scene->id;
04388 }
04389 
04390 static void link_paint(FileData *fd, Scene *sce, Paint *p)
04391 {
04392         if(p) {
04393                 p->brush= newlibadr_us(fd, sce->id.lib, p->brush);
04394                 p->paint_cursor= NULL;
04395         }
04396 }
04397 
04398 static void lib_link_scene(FileData *fd, Main *main)
04399 {
04400         Scene *sce;
04401         Base *base, *next;
04402         Sequence *seq;
04403         SceneRenderLayer *srl;
04404         TimeMarker *marker;
04405         
04406         sce= main->scene.first;
04407         while(sce) {
04408                 if(sce->id.flag & LIB_NEEDLINK) {
04409                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
04410                         of library blocks that implement this.*/
04411                         if (sce->id.properties) IDP_LibLinkProperty(sce->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
04412                         if (sce->adt) lib_link_animdata(fd, &sce->id, sce->adt);
04413                         
04414                         lib_link_keyingsets(fd, &sce->id, &sce->keyingsets);
04415                         
04416                         sce->camera= newlibadr(fd, sce->id.lib, sce->camera);
04417                         sce->world= newlibadr_us(fd, sce->id.lib, sce->world);
04418                         sce->set= newlibadr(fd, sce->id.lib, sce->set);
04419                         sce->gpd= newlibadr_us(fd, sce->id.lib, sce->gpd);
04420                         
04421                         link_paint(fd, sce, &sce->toolsettings->sculpt->paint);
04422                         link_paint(fd, sce, &sce->toolsettings->vpaint->paint);
04423                         link_paint(fd, sce, &sce->toolsettings->wpaint->paint);
04424                         link_paint(fd, sce, &sce->toolsettings->imapaint.paint);
04425 
04426                         sce->toolsettings->skgen_template = newlibadr(fd, sce->id.lib, sce->toolsettings->skgen_template);
04427 
04428                         for(base= sce->base.first; base; base= next) {
04429                                 next= base->next;
04430 
04431                                 /* base->object= newlibadr_us(fd, sce->id.lib, base->object); */
04432                                 base->object= newlibadr_us(fd, sce->id.lib, base->object);
04433                                 
04434                                 if(base->object==NULL) {
04435                                         BKE_reportf(fd->reports, RPT_ERROR, "LIB ERROR: Object lost from scene:'%s\'\n", sce->id.name+2);
04436                                         if(G.background==0) printf("LIB ERROR: base removed from scene:'%s\'\n", sce->id.name+2);
04437                                         BLI_remlink(&sce->base, base);
04438                                         if(base==sce->basact) sce->basact= NULL;
04439                                         MEM_freeN(base);
04440                                 }
04441                         }
04442 
04443                         SEQ_BEGIN(sce->ed, seq) {
04444                                 if(seq->ipo) seq->ipo= newlibadr_us(fd, sce->id.lib, seq->ipo);
04445                                 seq->scene_sound = NULL;
04446                                 if(seq->scene) {
04447                                         seq->scene= newlibadr(fd, sce->id.lib, seq->scene);
04448                                         seq->scene_sound = sound_scene_add_scene_sound(sce, seq, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
04449                                 }
04450                                 if(seq->scene_camera) seq->scene_camera= newlibadr(fd, sce->id.lib, seq->scene_camera);
04451                                 if(seq->sound) {
04452                                         seq->scene_sound = NULL;
04453                                         if(seq->type == SEQ_HD_SOUND)
04454                                                 seq->type = SEQ_SOUND;
04455                                         else
04456                                                 seq->sound= newlibadr(fd, sce->id.lib, seq->sound);
04457                                         if (seq->sound) {
04458                                                 seq->sound->id.us++;
04459                                                 seq->scene_sound = sound_add_scene_sound(sce, seq, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
04460                                         }
04461                                 }
04462                                 seq->anim= NULL;
04463                         }
04464                         SEQ_END
04465 
04466 #ifdef DURIAN_CAMERA_SWITCH
04467                         for(marker= sce->markers.first; marker; marker= marker->next) {
04468                                 if(marker->camera) {
04469                                         marker->camera= newlibadr(fd, sce->id.lib, marker->camera);
04470                                 }
04471                         }
04472 #endif
04473 
04474                         if(sce->ed)
04475                                 seq_update_muting(sce, sce->ed);
04476                         
04477                         if(sce->nodetree) {
04478                                 lib_link_ntree(fd, &sce->id, sce->nodetree);
04479                                 composite_patch(sce->nodetree, sce);
04480                         }
04481                         
04482                         for(srl= sce->r.layers.first; srl; srl= srl->next) {
04483                                 srl->mat_override= newlibadr_us(fd, sce->id.lib, srl->mat_override);
04484                                 srl->light_override= newlibadr_us(fd, sce->id.lib, srl->light_override);
04485                         }
04486                         /*Game Settings: Dome Warp Text*/
04487                         sce->gm.dome.warptext= newlibadr(fd, sce->id.lib, sce->gm.dome.warptext);
04488 
04489                         sce->id.flag -= LIB_NEEDLINK;
04490                 }
04491 
04492                 sce= sce->id.next;
04493         }
04494 }
04495 
04496 static void link_recurs_seq(FileData *fd, ListBase *lb)
04497 {
04498         Sequence *seq;
04499 
04500         link_list(fd, lb);
04501 
04502         for(seq=lb->first; seq; seq=seq->next)
04503                 if(seq->seqbase.first)
04504                         link_recurs_seq(fd, &seq->seqbase);
04505 }
04506 
04507 static void direct_link_paint(FileData *fd, Paint **paint)
04508 {
04509 /* TODO. is this needed */
04510         (*paint)= newdataadr(fd, (*paint));
04511 }
04512 
04513 static void direct_link_scene(FileData *fd, Scene *sce)
04514 {
04515         Editing *ed;
04516         Sequence *seq;
04517         MetaStack *ms;
04518 
04519         sce->theDag = NULL;
04520         sce->dagisvalid = 0;
04521         sce->obedit= NULL;
04522         sce->stats= NULL;
04523         sce->fps_info= NULL;
04524         sce->customdata_mask_modal= 0;
04525         sce->lay_updated = 0;
04526 
04527         sound_create_scene(sce);
04528 
04529         /* set users to one by default, not in lib-link, this will increase it for compo nodes */
04530         sce->id.us= 1;
04531 
04532         link_list(fd, &(sce->base));
04533         
04534         sce->adt= newdataadr(fd, sce->adt);
04535         direct_link_animdata(fd, sce->adt);
04536         
04537         link_list(fd, &sce->keyingsets);
04538         direct_link_keyingsets(fd, &sce->keyingsets);
04539         
04540         sce->basact= newdataadr(fd, sce->basact);
04541         
04542         sce->toolsettings= newdataadr(fd, sce->toolsettings);
04543         if(sce->toolsettings) {
04544                 direct_link_paint(fd, (Paint**)&sce->toolsettings->sculpt);
04545                 direct_link_paint(fd, (Paint**)&sce->toolsettings->vpaint);
04546                 direct_link_paint(fd, (Paint**)&sce->toolsettings->wpaint);
04547 
04548                 sce->toolsettings->imapaint.paintcursor= NULL;
04549                 sce->toolsettings->particle.paintcursor= NULL;
04550         }
04551 
04552         if(sce->ed) {
04553                 ListBase *old_seqbasep= &((Editing *)sce->ed)->seqbase;
04554                 
04555                 ed= sce->ed= newdataadr(fd, sce->ed);
04556 
04557                 ed->act_seq= newdataadr(fd, ed->act_seq);
04558 
04559                 /* recursive link sequences, lb will be correctly initialized */
04560                 link_recurs_seq(fd, &ed->seqbase);
04561 
04562                 SEQ_BEGIN(ed, seq) {
04563                         seq->seq1= newdataadr(fd, seq->seq1);
04564                         seq->seq2= newdataadr(fd, seq->seq2);
04565                         seq->seq3= newdataadr(fd, seq->seq3);
04566                         /* a patch: after introduction of effects with 3 input strips */
04567                         if(seq->seq3==NULL) seq->seq3= seq->seq2;
04568 
04569                         seq->plugin= newdataadr(fd, seq->plugin);
04570                         seq->effectdata= newdataadr(fd, seq->effectdata);
04571                         
04572                         if(seq->type & SEQ_EFFECT)
04573                                 seq->flag |= SEQ_EFFECT_NOT_LOADED;
04574 
04575                         if(seq->type == SEQ_SPEED) {
04576                                 SpeedControlVars *s= seq->effectdata;
04577                                 s->frameMap= NULL;
04578                         }
04579 
04580                         seq->strip= newdataadr(fd, seq->strip);
04581                         if(seq->strip && seq->strip->done==0) {
04582                                 seq->strip->done= 1;
04583 
04584                                 if(seq->type == SEQ_IMAGE ||
04585                                    seq->type == SEQ_MOVIE ||
04586                                    seq->type == SEQ_RAM_SOUND ||
04587                                    seq->type == SEQ_HD_SOUND) {
04588                                         seq->strip->stripdata = newdataadr(
04589                                                 fd, seq->strip->stripdata);
04590                                 } else {
04591                                         seq->strip->stripdata = NULL;
04592                                 }
04593                                 if (seq->flag & SEQ_USE_CROP) {
04594                                         seq->strip->crop = newdataadr(
04595                                                 fd, seq->strip->crop);
04596                                 } else {
04597                                         seq->strip->crop = NULL;
04598                                 }
04599                                 if (seq->flag & SEQ_USE_TRANSFORM) {
04600                                         seq->strip->transform = newdataadr(
04601                                                 fd, seq->strip->transform);
04602                                 } else {
04603                                         seq->strip->transform = NULL;
04604                                 }
04605                                 if (seq->flag & SEQ_USE_PROXY) {
04606                                         seq->strip->proxy = newdataadr(
04607                                                 fd, seq->strip->proxy);
04608                                         seq->strip->proxy->anim = NULL;
04609                                 } else {
04610                                         seq->strip->proxy = NULL;
04611                                 }
04612                                 if (seq->flag & SEQ_USE_COLOR_BALANCE) {
04613                                         seq->strip->color_balance = newdataadr(
04614                                                 fd, seq->strip->color_balance);
04615                                 } else {
04616                                         seq->strip->color_balance = NULL;
04617                                 }
04618                                 if (seq->strip->color_balance) {
04619                                         // seq->strip->color_balance->gui = 0; // XXX - peter, is this relevant in 2.5?
04620                                 }
04621                         }
04622                 }
04623                 SEQ_END
04624                 
04625                 /* link metastack, slight abuse of structs here, have to restore pointer to internal part in struct */
04626                 {
04627                         Sequence temp;
04628                         char *poin;
04629                         intptr_t offset;
04630                         
04631                         offset= ((intptr_t)&(temp.seqbase)) - ((intptr_t)&temp);
04632                         
04633                         /* root pointer */
04634                         if(ed->seqbasep == old_seqbasep) {
04635                                 ed->seqbasep= &ed->seqbase;
04636                         }
04637                         else {
04638                                 
04639                                 poin= (char *)ed->seqbasep;
04640                                 poin -= offset;
04641                                 
04642                                 poin= newdataadr(fd, poin);
04643                                 if(poin) ed->seqbasep= (ListBase *)(poin+offset);
04644                                 else ed->seqbasep= &ed->seqbase;
04645                         }                       
04646                         /* stack */
04647                         link_list(fd, &(ed->metastack));
04648                         
04649                         for(ms= ed->metastack.first; ms; ms= ms->next) {
04650                                 ms->parseq= newdataadr(fd, ms->parseq);
04651                                 
04652                                 if(ms->oldbasep == old_seqbasep)
04653                                         ms->oldbasep= &ed->seqbase;
04654                                 else {
04655                                         poin= (char *)ms->oldbasep;
04656                                         poin -= offset;
04657                                         poin= newdataadr(fd, poin);
04658                                         if(poin) ms->oldbasep= (ListBase *)(poin+offset);
04659                                         else ms->oldbasep= &ed->seqbase;
04660                                 }
04661                         }
04662                 }
04663         }
04664         
04665         sce->r.avicodecdata = newdataadr(fd, sce->r.avicodecdata);
04666         if (sce->r.avicodecdata) {
04667                 sce->r.avicodecdata->lpFormat = newdataadr(fd, sce->r.avicodecdata->lpFormat);
04668                 sce->r.avicodecdata->lpParms = newdataadr(fd, sce->r.avicodecdata->lpParms);
04669         }
04670         
04671         sce->r.qtcodecdata = newdataadr(fd, sce->r.qtcodecdata);
04672         if (sce->r.qtcodecdata) {
04673                 sce->r.qtcodecdata->cdParms = newdataadr(fd, sce->r.qtcodecdata->cdParms);
04674         }
04675         if (sce->r.ffcodecdata.properties) {
04676                 sce->r.ffcodecdata.properties = newdataadr(
04677                         fd, sce->r.ffcodecdata.properties);
04678                 if (sce->r.ffcodecdata.properties) { 
04679                         IDP_DirectLinkProperty(
04680                                 sce->r.ffcodecdata.properties, 
04681                                 (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
04682                 }
04683         }
04684 
04685         link_list(fd, &(sce->markers));
04686         link_list(fd, &(sce->transform_spaces));
04687         link_list(fd, &(sce->r.layers));
04688 
04689         sce->nodetree= newdataadr(fd, sce->nodetree);
04690         if(sce->nodetree)
04691                 direct_link_nodetree(fd, sce->nodetree);
04692         
04693 }
04694 
04695 /* ************ READ WM ***************** */
04696 
04697 static void direct_link_windowmanager(FileData *fd, wmWindowManager *wm)
04698 {
04699         wmWindow *win;
04700         
04701         wm->id.us= 1;
04702         link_list(fd, &(wm->windows));
04703         
04704         for(win= wm->windows.first; win; win= win->next) {
04705                 win->ghostwin= NULL;
04706                 win->eventstate= NULL;
04707                 win->curswin= NULL;
04708                 win->tweak= NULL;
04709 
04710                 win->queue.first= win->queue.last= NULL;
04711                 win->handlers.first= win->handlers.last= NULL;
04712                 win->modalhandlers.first= win->modalhandlers.last= NULL;
04713                 win->subwindows.first= win->subwindows.last= NULL;
04714                 win->gesture.first= win->gesture.last= NULL;
04715 
04716                 win->drawdata= NULL;
04717                 win->drawmethod= -1;
04718                 win->drawfail= 0;
04719         }
04720         
04721         wm->timers.first= wm->timers.last= NULL;
04722         wm->operators.first= wm->operators.last= NULL;
04723         wm->paintcursors.first= wm->paintcursors.last= NULL;
04724         wm->queue.first= wm->queue.last= NULL;
04725         BKE_reports_init(&wm->reports, RPT_STORE);
04726 
04727         wm->keyconfigs.first= wm->keyconfigs.last= NULL;
04728         wm->defaultconf= NULL;
04729         wm->addonconf= NULL;
04730         wm->userconf= NULL;
04731 
04732         wm->jobs.first= wm->jobs.last= NULL;
04733         wm->drags.first= wm->drags.last= NULL;
04734         
04735         wm->windrawable= NULL;
04736         wm->winactive= NULL;
04737         wm->initialized= 0;
04738         wm->op_undo_depth= 0;
04739 }
04740 
04741 static void lib_link_windowmanager(FileData *fd, Main *main)
04742 {
04743         wmWindowManager *wm;
04744         wmWindow *win;
04745         
04746         for(wm= main->wm.first; wm; wm= wm->id.next) {
04747                 if(wm->id.flag & LIB_NEEDLINK) {
04748                         for(win= wm->windows.first; win; win= win->next)
04749                                 win->screen= newlibadr(fd, NULL, win->screen);
04750 
04751                         wm->id.flag -= LIB_NEEDLINK;
04752                 }
04753         }
04754 }
04755 
04756 /* ****************** READ GREASE PENCIL ***************** */
04757 
04758 /* relinks grease-pencil data - used for direct_link and old file linkage */
04759 static void direct_link_gpencil(FileData *fd, bGPdata *gpd)
04760 {
04761         bGPDlayer *gpl;
04762         bGPDframe *gpf;
04763         bGPDstroke *gps;
04764         
04765         /* we must firstly have some grease-pencil data to link! */
04766         if (gpd == NULL)
04767                 return;
04768         
04769         /* relink layers */
04770         link_list(fd, &gpd->layers);
04771         
04772         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
04773                 /* relink frames */
04774                 link_list(fd, &gpl->frames);
04775                 gpl->actframe= newdataadr(fd, gpl->actframe);
04776                 
04777                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
04778                         /* relink strokes (and their points) */
04779                         link_list(fd, &gpf->strokes);
04780                         
04781                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
04782                                 gps->points= newdataadr(fd, gps->points);
04783                         }
04784                 }
04785         }
04786 }
04787 
04788 /* ****************** READ SCREEN ***************** */
04789 
04790 static void butspace_version_132(SpaceButs *buts)
04791 {
04792         buts->v2d.tot.xmin= 0.0f;
04793         buts->v2d.tot.ymin= 0.0f;
04794         buts->v2d.tot.xmax= 1279.0f;
04795         buts->v2d.tot.ymax= 228.0f;
04796 
04797         buts->v2d.min[0]= 256.0f;
04798         buts->v2d.min[1]= 42.0f;
04799 
04800         buts->v2d.max[0]= 2048.0f;
04801         buts->v2d.max[1]= 450.0f;
04802 
04803         buts->v2d.minzoom= 0.5f;
04804         buts->v2d.maxzoom= 1.21f;
04805 
04806         buts->v2d.scroll= 0;
04807         buts->v2d.keepzoom= 1;
04808         buts->v2d.keeptot= 1;
04809 }
04810 
04811 /* note: file read without screens option G_FILE_NO_UI; 
04812    check lib pointers in call below */
04813 static void lib_link_screen(FileData *fd, Main *main)
04814 {
04815         bScreen *sc;
04816         ScrArea *sa;
04817 
04818         for(sc= main->screen.first; sc; sc= sc->id.next) {
04819                 if(sc->id.flag & LIB_NEEDLINK) {
04820                         sc->id.us= 1;
04821                         sc->scene= newlibadr(fd, sc->id.lib, sc->scene);
04822                         sc->animtimer= NULL; /* saved in rare cases */
04823                         
04824                         sa= sc->areabase.first;
04825                         while(sa) {
04826                                 SpaceLink *sl;
04827                                 
04828                                 sa->full= newlibadr(fd, sc->id.lib, sa->full);
04829                                 
04830                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
04831                                         if(sl->spacetype==SPACE_VIEW3D) {
04832                                                 View3D *v3d= (View3D*) sl;
04833                                                 BGpic *bgpic = NULL;
04834                                                 
04835                                                 v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
04836                                                 v3d->ob_centre= newlibadr(fd, sc->id.lib, v3d->ob_centre);
04837                                                 
04838                                                 /* should be do_versions but not easy adding into the listbase */
04839                                                 if(v3d->bgpic) {
04840                                                         v3d->bgpic= newlibadr(fd, sc->id.lib, v3d->bgpic);
04841                                                         BLI_addtail(&v3d->bgpicbase, bgpic);
04842                                                         v3d->bgpic= NULL;
04843                                                 }
04844 
04845                                                 for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next) {
04846                                                         bgpic->ima= newlibadr_us(fd, sc->id.lib, bgpic->ima);
04847                                                 }
04848                                                 if(v3d->localvd) {
04849                                                         v3d->localvd->camera= newlibadr(fd, sc->id.lib, v3d->localvd->camera);
04850                                                 }
04851                                         }
04852                                         else if(sl->spacetype==SPACE_IPO) {
04853                                                 SpaceIpo *sipo= (SpaceIpo *)sl;
04854                                                 bDopeSheet *ads= sipo->ads;
04855                                                 
04856                                                 if (ads) {
04857                                                         ads->source= newlibadr(fd, sc->id.lib, ads->source);
04858                                                         ads->filter_grp= newlibadr(fd, sc->id.lib, ads->filter_grp);
04859                                                 }
04860                                         }
04861                                         else if(sl->spacetype==SPACE_BUTS) {
04862                                                 SpaceButs *sbuts= (SpaceButs *)sl;
04863                                                 sbuts->ri= NULL;
04864                                                 sbuts->pinid= newlibadr(fd, sc->id.lib, sbuts->pinid);
04865                                                 sbuts->mainbo= sbuts->mainb;
04866                                                 sbuts->mainbuser= sbuts->mainb;
04867                                                 if(main->versionfile<132)
04868                                                         butspace_version_132(sbuts);
04869                                         }
04870                                         else if(sl->spacetype==SPACE_FILE) {
04871                                                 SpaceFile *sfile= (SpaceFile *)sl;
04872                                                 sfile->files= NULL;
04873                                                 sfile->op= NULL;
04874                                                 sfile->layout= NULL;
04875                                                 sfile->folders_prev= NULL;
04876                                                 sfile->folders_next= NULL;
04877                                         }
04878                                         else if(sl->spacetype==SPACE_IMASEL) {
04879                                                 SpaceImaSel *simasel= (SpaceImaSel *)sl;
04880 
04881                                                 simasel->files = NULL;                                          
04882                                                 simasel->returnfunc= NULL;
04883                                                 simasel->menup= NULL;
04884                                                 simasel->pupmenu= NULL;
04885                                                 simasel->img= NULL;
04886                                         }
04887                                         else if(sl->spacetype==SPACE_ACTION) {
04888                                                 SpaceAction *saction= (SpaceAction *)sl;
04889                                                 bDopeSheet *ads= &saction->ads;
04890                                                 
04891                                                 if (ads) {
04892                                                         ads->source= newlibadr(fd, sc->id.lib, ads->source);
04893                                                         ads->filter_grp= newlibadr(fd, sc->id.lib, ads->filter_grp);
04894                                                 }
04895                                                 
04896                                                 saction->action = newlibadr(fd, sc->id.lib, saction->action);
04897                                         }
04898                                         else if(sl->spacetype==SPACE_IMAGE) {
04899                                                 SpaceImage *sima= (SpaceImage *)sl;
04900 
04901                                                 sima->image= newlibadr_us(fd, sc->id.lib, sima->image);
04902                                                 
04903                                                 /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data
04904                                                  * so fingers crossed this works fine!
04905                                                  */
04906                                                 sima->gpd= newlibadr_us(fd, sc->id.lib, sima->gpd);
04907                                         }
04908                                         else if(sl->spacetype==SPACE_NLA){
04909                                                 SpaceNla *snla= (SpaceNla *)sl;
04910                                                 bDopeSheet *ads= snla->ads;
04911                                                 
04912                                                 if (ads) {
04913                                                         ads->source= newlibadr(fd, sc->id.lib, ads->source);
04914                                                         ads->filter_grp= newlibadr(fd, sc->id.lib, ads->filter_grp);
04915                                                 }
04916                                         }
04917                                         else if(sl->spacetype==SPACE_TEXT) {
04918                                                 SpaceText *st= (SpaceText *)sl;
04919 
04920                                                 st->text= newlibadr(fd, sc->id.lib, st->text);
04921                                                 st->drawcache= NULL;
04922 
04923                                         }
04924                                         else if(sl->spacetype==SPACE_SCRIPT) {
04925 
04926                                                 SpaceScript *scpt= (SpaceScript *)sl;
04927                                                 /*scpt->script = NULL; - 2.45 set to null, better re-run the script */
04928                                                 if (scpt->script) {
04929                                                         scpt->script= newlibadr(fd, sc->id.lib, scpt->script);
04930                                                         if (scpt->script) {
04931                                                                 SCRIPT_SET_NULL(scpt->script)
04932                                                         }
04933                                                 }
04934                                         }
04935                                         else if(sl->spacetype==SPACE_OUTLINER) {
04936                                                 SpaceOops *so= (SpaceOops *)sl;
04937                                                 TreeStoreElem *tselem;
04938                                                 int a;
04939 
04940                                                 so->tree.first= so->tree.last= NULL;
04941                                                 so->search_tse.id= newlibadr(fd, NULL, so->search_tse.id);
04942                                                 
04943                                                 if(so->treestore) {
04944                                                         tselem= so->treestore->data;
04945                                                         for(a=0; a<so->treestore->usedelem; a++, tselem++) {
04946                                                                 tselem->id= newlibadr(fd, NULL, tselem->id);
04947                                                         }
04948                                                 }
04949                                         }
04950                                         else if(sl->spacetype==SPACE_SOUND) {
04951                                                 SpaceSound *ssound= (SpaceSound *)sl;
04952 
04953                                                 ssound->sound= newlibadr_us(fd, sc->id.lib, ssound->sound);
04954                                         }
04955                                         else if(sl->spacetype==SPACE_NODE) {
04956                                                 SpaceNode *snode= (SpaceNode *)sl;
04957                                                 
04958                                                 snode->id= newlibadr(fd, sc->id.lib, snode->id);
04959                                                 
04960                                                 /* internal data, a bit patchy */
04961                                                 if(snode->id) {
04962                                                         if(GS(snode->id->name)==ID_MA)
04963                                                                 snode->nodetree= ((Material *)snode->id)->nodetree;
04964                                                         else if(GS(snode->id->name)==ID_SCE)
04965                                                                 snode->nodetree= ((Scene *)snode->id)->nodetree;
04966                                                         else if(GS(snode->id->name)==ID_TE)
04967                                                                 snode->nodetree= ((Tex *)snode->id)->nodetree;
04968                                                 }
04969                                                 
04970                                                 snode->linkdrag.first = snode->linkdrag.last = NULL;
04971                                         }
04972                                 }
04973                                 sa= sa->next;
04974                         }
04975                         sc->id.flag -= LIB_NEEDLINK;
04976                 }
04977         }
04978 }
04979 
04980 /* Only for undo files, or to restore a screen after reading without UI... */
04981 static void *restore_pointer_by_name(Main *mainp, ID *id, int user)
04982 {
04983                 
04984         if(id) {
04985                 ListBase *lb= which_libbase(mainp, GS(id->name));
04986                 
04987                 if(lb) {        // there's still risk of checking corrupt mem (freed Ids in oops)
04988                         ID *idn= lb->first;
04989                         char *name= id->name+2;
04990                         
04991                         while(idn) {
04992                                 if(idn->name[2]==name[0] && strcmp(idn->name+2, name)==0) {
04993                                         if(idn->lib==id->lib) {
04994                                                 if(user && idn->us==0) idn->us++;
04995                                                 break;
04996                                         }
04997                                 }
04998                                 idn= idn->next;
04999                         }
05000                         return idn;
05001                 }
05002         }
05003         return NULL;
05004 }
05005 
05006 /* called from kernel/blender.c */
05007 /* used to link a file (without UI) to the current UI */
05008 /* note that it assumes the old pointers in UI are still valid, so old Main is not freed */
05009 void lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *curscene)
05010 {
05011         wmWindow *win;
05012         wmWindowManager *wm;
05013         bScreen *sc;
05014         ScrArea *sa;
05015 
05016         /* first windowmanager */
05017         for(wm= newmain->wm.first; wm; wm= wm->id.next) {
05018                 for(win= wm->windows.first; win; win= win->next) {
05019                         win->screen= restore_pointer_by_name(newmain, (ID *)win->screen, 1);
05020                         
05021                         if(win->screen==NULL)
05022                                 win->screen= curscreen;
05023 
05024                         win->screen->winid= win->winid;
05025                 }
05026         }
05027         
05028         
05029         for(sc= newmain->screen.first; sc; sc= sc->id.next) {
05030                 Scene *oldscene= sc->scene;
05031 
05032                 sc->scene= restore_pointer_by_name(newmain, (ID *)sc->scene, 1);
05033                 if(sc->scene==NULL)
05034                         sc->scene= curscene;
05035 
05036                 /* keep cursor location through undo */
05037                 copy_v3_v3(sc->scene->cursor, oldscene->cursor);
05038 
05039                 sa= sc->areabase.first;
05040                 while(sa) {
05041                         SpaceLink *sl;
05042 
05043                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
05044                                 if(sl->spacetype==SPACE_VIEW3D) {
05045                                         View3D *v3d= (View3D*) sl;
05046                                         BGpic *bgpic;
05047                                         
05048                                         if(v3d->scenelock)
05049                                                 v3d->camera= NULL; /* always get from scene */
05050                                         else
05051                                                 v3d->camera= restore_pointer_by_name(newmain, (ID *)v3d->camera, 1);
05052                                         if(v3d->camera==NULL)
05053                                                 v3d->camera= sc->scene->camera;
05054                                         v3d->ob_centre= restore_pointer_by_name(newmain, (ID *)v3d->ob_centre, 1);
05055                                         
05056                                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next) {
05057                                                 bgpic->ima= restore_pointer_by_name(newmain, (ID *)bgpic->ima, 1);
05058                                         }
05059                                         if(v3d->localvd) {
05060                                                 /*Base *base;*/
05061 
05062                                                 v3d->localvd->camera= sc->scene->camera;
05063                                                 
05064                                                 /* localview can become invalid during undo/redo steps, so we exit it when no could be found */
05065                                                 /* XXX  regionlocalview ?
05066                                                 for(base= sc->scene->base.first; base; base= base->next) {
05067                                                         if(base->lay & v3d->lay) break;
05068                                                 }
05069                                                 if(base==NULL) {
05070                                                         v3d->lay= v3d->localvd->lay;
05071                                                         v3d->layact= v3d->localvd->layact;
05072                                                         MEM_freeN(v3d->localvd); 
05073                                                         v3d->localvd= NULL;
05074                                                 }
05075                                                 */
05076                                         }
05077                                         else if(v3d->scenelock) v3d->lay= sc->scene->lay;
05078 
05079                                         /* not very nice, but could help */
05080                                         if((v3d->layact & v3d->lay)==0) v3d->layact= v3d->lay;
05081                                         
05082                                 }
05083                                 else if(sl->spacetype==SPACE_IPO) {
05084                                         SpaceIpo *sipo= (SpaceIpo *)sl;
05085                                         bDopeSheet *ads= sipo->ads;
05086                                         
05087                                         if (ads) {
05088                                                 ads->source= restore_pointer_by_name(newmain, (ID *)ads->source, 1);
05089                                                 
05090                                                 if (ads->filter_grp)
05091                                                         ads->filter_grp= restore_pointer_by_name(newmain, (ID *)ads->filter_grp, 0);
05092                                         }
05093                                 }
05094                                 else if(sl->spacetype==SPACE_BUTS) {
05095                                         SpaceButs *sbuts= (SpaceButs *)sl;
05096                                         sbuts->pinid = restore_pointer_by_name(newmain, sbuts->pinid, 0);
05097                                         //XXX if (sbuts->ri) sbuts->ri->curtile = 0;
05098                                 }
05099                                 else if(sl->spacetype==SPACE_FILE) {
05100                                         
05101                                         SpaceFile *sfile= (SpaceFile *)sl;
05102                                         sfile->op= NULL;
05103                                 }
05104                                 else if(sl->spacetype==SPACE_IMASEL) {
05105                                         SpaceImaSel *simasel= (SpaceImaSel *)sl;
05106                                         if (simasel->files) {
05107                                                 //XXX BIF_filelist_freelib(simasel->files);
05108                                         }
05109                                 }
05110                                 else if(sl->spacetype==SPACE_ACTION) {
05111                                         SpaceAction *saction= (SpaceAction *)sl;
05112                                         
05113                                         saction->action = restore_pointer_by_name(newmain, (ID *)saction->action, 1);
05114                                         saction->ads.source= restore_pointer_by_name(newmain, (ID *)saction->ads.source, 1);
05115 
05116                                         if (saction->ads.filter_grp)
05117                                                 saction->ads.filter_grp= restore_pointer_by_name(newmain, (ID *)saction->ads.filter_grp, 0);
05118                                 }
05119                                 else if(sl->spacetype==SPACE_IMAGE) {
05120                                         SpaceImage *sima= (SpaceImage *)sl;
05121 
05122                                         sima->image= restore_pointer_by_name(newmain, (ID *)sima->image, 1);
05123 
05124                                         sima->scopes.waveform_1 = NULL;
05125                                         sima->scopes.waveform_2 = NULL;
05126                                         sima->scopes.waveform_3 = NULL;
05127                                         sima->scopes.vecscope = NULL;
05128                                         sima->scopes.ok = 0;
05129                                         
05130                                         /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data
05131                                          * so assume that here we're doing for undo only...
05132                                          */
05133                                         sima->gpd= restore_pointer_by_name(newmain, (ID *)sima->gpd, 1);
05134                                 }
05135                                 else if(sl->spacetype==SPACE_NLA){
05136                                         SpaceNla *snla= (SpaceNla *)sl;
05137                                         bDopeSheet *ads= snla->ads;
05138                                         
05139                                         if (ads) {
05140                                                 ads->source= restore_pointer_by_name(newmain, (ID *)ads->source, 1);
05141                                                 
05142                                                 if (ads->filter_grp)
05143                                                         ads->filter_grp= restore_pointer_by_name(newmain, (ID *)ads->filter_grp, 0);
05144                                         }
05145                                 }
05146                                 else if(sl->spacetype==SPACE_TEXT) {
05147                                         SpaceText *st= (SpaceText *)sl;
05148 
05149                                         st->text= restore_pointer_by_name(newmain, (ID *)st->text, 1);
05150                                         if(st->text==NULL) st->text= newmain->text.first;
05151                                 }
05152                                 else if(sl->spacetype==SPACE_SCRIPT) {
05153                                         SpaceScript *scpt= (SpaceScript *)sl;
05154                                         
05155                                         scpt->script= restore_pointer_by_name(newmain, (ID *)scpt->script, 1);
05156                                         
05157                                         /*sc->script = NULL; - 2.45 set to null, better re-run the script */
05158                                         if (scpt->script) {
05159                                                 SCRIPT_SET_NULL(scpt->script)
05160                                         }
05161                                 }
05162                                 else if(sl->spacetype==SPACE_OUTLINER) {
05163                                         SpaceOops *so= (SpaceOops *)sl;
05164                                         int a;
05165                                         
05166                                         so->search_tse.id= restore_pointer_by_name(newmain, so->search_tse.id, 0);
05167                                         
05168                                         if(so->treestore) {
05169                                                 TreeStore *ts= so->treestore;
05170                                                 TreeStoreElem *tselem=ts->data;
05171                                                 for(a=0; a<ts->usedelem; a++, tselem++) {
05172                                                         tselem->id= restore_pointer_by_name(newmain, tselem->id, 0);
05173                                                 }
05174                                         }
05175                                 }
05176                                 else if(sl->spacetype==SPACE_SOUND) {
05177                                         SpaceSound *ssound= (SpaceSound *)sl;
05178 
05179                                         ssound->sound= restore_pointer_by_name(newmain, (ID *)ssound->sound, 1);
05180                                 }
05181                                 else if(sl->spacetype==SPACE_NODE) {
05182                                         SpaceNode *snode= (SpaceNode *)sl;
05183                                         
05184                                         snode->id= restore_pointer_by_name(newmain, snode->id, 1);
05185                                         snode->edittree= NULL;
05186                                         
05187                                         if(snode->id==NULL)
05188                                                 snode->nodetree= NULL;
05189                                         else {
05190                                                 if(GS(snode->id->name)==ID_MA)
05191                                                         snode->nodetree= ((Material *)snode->id)->nodetree;
05192                                                 else if(GS(snode->id->name)==ID_SCE)
05193                                                         snode->nodetree= ((Scene *)snode->id)->nodetree;
05194                                                 else if(GS(snode->id->name)==ID_TE)
05195                                                         snode->nodetree= ((Tex *)snode->id)->nodetree;
05196                                         }
05197                                 }
05198                         }
05199                         sa= sa->next;
05200                 }
05201         }
05202 }
05203 
05204 static void direct_link_region(FileData *fd, ARegion *ar, int spacetype)
05205 {
05206         Panel *pa;
05207 
05208         link_list(fd, &(ar->panels));
05209 
05210         for(pa= ar->panels.first; pa; pa=pa->next) {
05211                 pa->paneltab= newdataadr(fd, pa->paneltab);
05212                 pa->runtime_flag= 0;
05213                 pa->activedata= NULL;
05214                 pa->type= NULL;
05215         }
05216         
05217         ar->regiondata= newdataadr(fd, ar->regiondata);
05218         if(ar->regiondata) {
05219                 if(spacetype==SPACE_VIEW3D) {
05220                         RegionView3D *rv3d= ar->regiondata;
05221                         
05222                         rv3d->localvd= newdataadr(fd, rv3d->localvd);
05223                         rv3d->clipbb= newdataadr(fd, rv3d->clipbb);
05224                         
05225                         rv3d->depths= NULL;
05226                         rv3d->ri= NULL;
05227                         rv3d->sms= NULL;
05228                         rv3d->smooth_timer= NULL;
05229                 }
05230         }
05231         
05232         ar->v2d.tab_offset= NULL;
05233         ar->v2d.tab_num= 0;
05234         ar->v2d.tab_cur= 0;
05235         ar->handlers.first= ar->handlers.last= NULL;
05236         ar->uiblocks.first= ar->uiblocks.last= NULL;
05237         ar->headerstr= NULL;
05238         ar->swinid= 0;
05239         ar->type= NULL;
05240         ar->swap= 0;
05241         ar->do_draw= 0;
05242         memset(&ar->drawrct, 0, sizeof(ar->drawrct));
05243 }
05244 
05245 /* for the saved 2.50 files without regiondata */
05246 /* and as patch for 2.48 and older */
05247 static void view3d_split_250(View3D *v3d, ListBase *regions)
05248 {
05249         ARegion *ar;
05250         
05251         for(ar= regions->first; ar; ar= ar->next) {
05252                 if(ar->regiontype==RGN_TYPE_WINDOW && ar->regiondata==NULL) {
05253                         RegionView3D *rv3d;
05254                         
05255                         rv3d= ar->regiondata= MEM_callocN(sizeof(RegionView3D), "region v3d patch");
05256                         rv3d->persp= v3d->persp;
05257                         rv3d->view= v3d->view;
05258                         rv3d->dist= v3d->dist;
05259                         VECCOPY(rv3d->ofs, v3d->ofs);
05260                         QUATCOPY(rv3d->viewquat, v3d->viewquat);
05261                 }
05262         }
05263 
05264         /* this was not initialized correct always */
05265         if(v3d->twtype == 0)
05266                 v3d->twtype= V3D_MANIP_TRANSLATE;
05267 }
05268 
05269 static void direct_link_screen(FileData *fd, bScreen *sc)
05270 {
05271         ScrArea *sa;
05272         ScrVert *sv;
05273         ScrEdge *se;
05274         int a;
05275         
05276         link_list(fd, &(sc->vertbase));
05277         link_list(fd, &(sc->edgebase));
05278         link_list(fd, &(sc->areabase));
05279         sc->regionbase.first= sc->regionbase.last= NULL;
05280         sc->context= NULL;
05281 
05282         sc->mainwin= sc->subwinactive= 0;       /* indices */
05283         sc->swap= 0;
05284         
05285         /* hacky patch... but people have been saving files with the verse-blender,
05286            causing the handler to keep running for ever, with no means to disable it */
05287         for(a=0; a<SCREEN_MAXHANDLER; a+=2) {
05288                 if( sc->handler[a]==SCREEN_HANDLER_VERSE) {
05289                         sc->handler[a]= 0;
05290                         break;
05291                 }
05292         }
05293         
05294         /* edges */
05295         for(se= sc->edgebase.first; se; se= se->next) {
05296                 se->v1= newdataadr(fd, se->v1);
05297                 se->v2= newdataadr(fd, se->v2);
05298                 if( (intptr_t)se->v1 > (intptr_t)se->v2) {
05299                         sv= se->v1;
05300                         se->v1= se->v2;
05301                         se->v2= sv;
05302                 }
05303 
05304                 if(se->v1==NULL) {
05305                         printf("error reading screen... file corrupt\n");
05306                         se->v1= se->v2;
05307                 }
05308         }
05309 
05310         /* areas */
05311         for(sa= sc->areabase.first; sa; sa= sa->next) {
05312                 SpaceLink *sl;
05313                 ARegion *ar;
05314 
05315                 link_list(fd, &(sa->spacedata));
05316                 link_list(fd, &(sa->regionbase));
05317 
05318                 sa->handlers.first= sa->handlers.last= NULL;
05319                 sa->type= NULL; /* spacetype callbacks */
05320                 
05321                 for(ar= sa->regionbase.first; ar; ar= ar->next)
05322                         direct_link_region(fd, ar, sa->spacetype);
05323                 
05324                 /* accident can happen when read/save new file with older version */
05325                 /* 2.50: we now always add spacedata for info */
05326                 if(sa->spacedata.first==NULL) {
05327                         SpaceInfo *sinfo= MEM_callocN(sizeof(SpaceInfo), "spaceinfo");
05328                         sa->spacetype= sinfo->spacetype= SPACE_INFO;
05329                         BLI_addtail(&sa->spacedata, sinfo);
05330                 }
05331                 /* add local view3d too */
05332                 else if(sa->spacetype==SPACE_VIEW3D)
05333                         view3d_split_250(sa->spacedata.first, &sa->regionbase);
05334                 
05335                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
05336                         link_list(fd, &(sl->regionbase));
05337 
05338                         for(ar= sl->regionbase.first; ar; ar= ar->next)
05339                                 direct_link_region(fd, ar, sl->spacetype);
05340 
05341                         if (sl->spacetype==SPACE_VIEW3D) {
05342                                 View3D *v3d= (View3D*) sl;
05343                                 BGpic *bgpic;
05344 
05345                                 v3d->flag |= V3D_INVALID_BACKBUF;
05346 
05347                                 link_list(fd, &(v3d->bgpicbase));
05348 
05349                                 /* should be do_versions except this doesnt fit well there */
05350                                 if(v3d->bgpic) {
05351                                         bgpic= newdataadr(fd, v3d->bgpic);
05352                                         BLI_addtail(&v3d->bgpicbase, bgpic);
05353                                         v3d->bgpic= NULL;
05354                                 }
05355 
05356                                 for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
05357                                         bgpic->iuser.ok= 1;
05358 
05359                                 if(v3d->gpd) {
05360                                         v3d->gpd= newdataadr(fd, v3d->gpd);
05361                                         direct_link_gpencil(fd, v3d->gpd);
05362                                 }
05363                                 v3d->localvd= newdataadr(fd, v3d->localvd);
05364                                 v3d->afterdraw_transp.first= v3d->afterdraw_transp.last= NULL;
05365                                 v3d->afterdraw_xray.first= v3d->afterdraw_xray.last= NULL;
05366                                 v3d->afterdraw_xraytransp.first= v3d->afterdraw_xraytransp.last= NULL;
05367                                 v3d->properties_storage= NULL;
05368                                 
05369                                 view3d_split_250(v3d, &sl->regionbase);
05370                         }
05371                         else if (sl->spacetype==SPACE_IPO) {
05372                                 SpaceIpo *sipo= (SpaceIpo*)sl;
05373                                 
05374                                 sipo->ads= newdataadr(fd, sipo->ads);
05375                                 sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
05376                         }
05377                         else if (sl->spacetype==SPACE_NLA) {
05378                                 SpaceNla *snla= (SpaceNla*)sl;
05379                                 
05380                                 snla->ads= newdataadr(fd, snla->ads);
05381                         }
05382                         else if (sl->spacetype==SPACE_OUTLINER) {
05383                                 SpaceOops *soops= (SpaceOops*) sl;
05384                                 
05385                                 soops->treestore= newdataadr(fd, soops->treestore);
05386                                 if(soops->treestore) {
05387                                         soops->treestore->data= newdataadr(fd, soops->treestore->data);
05388                                         /* we only saved what was used */
05389                                         soops->treestore->totelem= soops->treestore->usedelem;
05390                                         soops->storeflag |= SO_TREESTORE_CLEANUP;       // at first draw
05391                                 }
05392                         }
05393                         else if(sl->spacetype==SPACE_IMAGE) {
05394                                 SpaceImage *sima= (SpaceImage *)sl;
05395                                 
05396                                 sima->cumap= newdataadr(fd, sima->cumap);
05397                                 if(sima->cumap)
05398                                         direct_link_curvemapping(fd, sima->cumap);
05399                                 
05400                                 sima->iuser.scene= NULL;
05401                                 sima->iuser.ok= 1;
05402                                 sima->scopes.waveform_1 = NULL;
05403                                 sima->scopes.waveform_2 = NULL;
05404                                 sima->scopes.waveform_3 = NULL;
05405                                 sima->scopes.vecscope = NULL;
05406                                 sima->scopes.ok = 0;
05407                                 
05408                                 /* WARNING: gpencil data is no longer stored directly in sima after 2.5 
05409                                  * so sacrifice a few old files for now to avoid crashes with new files!
05410                                  * committed: r28002 */
05411 #if 0
05412                                 sima->gpd= newdataadr(fd, sima->gpd);
05413                                 if (sima->gpd)
05414                                         direct_link_gpencil(fd, sima->gpd);
05415 #endif
05416                         }
05417                         else if(sl->spacetype==SPACE_NODE) {
05418                                 SpaceNode *snode= (SpaceNode *)sl;
05419                                 
05420                                 if(snode->gpd) {
05421                                         snode->gpd= newdataadr(fd, snode->gpd);
05422                                         direct_link_gpencil(fd, snode->gpd);
05423                                 }
05424                                 snode->nodetree= snode->edittree= NULL;
05425                         }
05426                         else if(sl->spacetype==SPACE_TIME) {
05427                                 SpaceTime *stime= (SpaceTime *)sl;
05428                                 stime->caches.first= stime->caches.last= NULL;
05429                         }
05430                         else if(sl->spacetype==SPACE_LOGIC) {
05431                                 SpaceLogic *slogic= (SpaceLogic *)sl;
05432                                         
05433                                 if(slogic->gpd) {
05434                                         slogic->gpd= newdataadr(fd, slogic->gpd);
05435                                         direct_link_gpencil(fd, slogic->gpd);
05436                                 }
05437                         }
05438                         else if(sl->spacetype==SPACE_SEQ) {
05439                                 SpaceSeq *sseq= (SpaceSeq *)sl;
05440                                 if(sseq->gpd) {
05441                                         sseq->gpd= newdataadr(fd, sseq->gpd);
05442                                         direct_link_gpencil(fd, sseq->gpd);
05443                                 }
05444                         }
05445                         else if(sl->spacetype==SPACE_BUTS) {
05446                                 SpaceButs *sbuts= (SpaceButs *)sl;
05447                                 sbuts->path= NULL;
05448                         }
05449                         else if(sl->spacetype==SPACE_CONSOLE) {
05450                                 SpaceConsole *sconsole= (SpaceConsole *)sl;
05451                                 ConsoleLine *cl, *cl_next;
05452                                 
05453                                 link_list(fd, &sconsole->scrollback);
05454                                 link_list(fd, &sconsole->history);
05455                                 
05456                                 //for(cl= sconsole->scrollback.first; cl; cl= cl->next)
05457                                 //      cl->line= newdataadr(fd, cl->line);
05458                                 
05459                                 /*comma expressions, (e.g. expr1, expr2, expr3) evalutate each expression,
05460                                   from left to right.  the right-most expression sets the result of the comma
05461                                   expression as a whole*/
05462                                 for(cl= sconsole->history.first; cl; cl= cl_next) {
05463                                         cl_next= cl->next;
05464                                         cl->line= newdataadr(fd, cl->line);
05465                                         if (cl->line) {
05466                                                 /* the allocted length is not written, so reset here */
05467                                                 cl->len_alloc= cl->len + 1;
05468                                         }
05469                                         else {
05470                                                 BLI_remlink(&sconsole->history, cl);
05471                                                 MEM_freeN(cl);
05472                                         }
05473                                 }
05474                         }
05475                         else if(sl->spacetype==SPACE_FILE) {
05476                                 SpaceFile *sfile= (SpaceFile *)sl;
05477                                 
05478                                 /* this sort of info is probably irrelevant for reloading...
05479                                  * plus, it isn't saved to files yet!
05480                                  */
05481                                 sfile->folders_prev= sfile->folders_next= NULL;
05482                                 sfile->files= NULL;
05483                                 sfile->layout= NULL;
05484                                 sfile->op= NULL;
05485                                 sfile->params= newdataadr(fd, sfile->params);
05486                         }
05487                 }
05488                 
05489                 sa->actionzones.first= sa->actionzones.last= NULL;
05490 
05491                 sa->v1= newdataadr(fd, sa->v1);
05492                 sa->v2= newdataadr(fd, sa->v2);
05493                 sa->v3= newdataadr(fd, sa->v3);
05494                 sa->v4= newdataadr(fd, sa->v4);
05495         }
05496 }
05497 
05498 /* ********** READ LIBRARY *************** */
05499 
05500 
05501 static void direct_link_library(FileData *fd, Library *lib, Main *main)
05502 {
05503         Main *newmain;
05504         
05505         for(newmain= fd->mainlist.first; newmain; newmain= newmain->next) {
05506                 if(newmain->curlib) {
05507                         if(BLI_path_cmp(newmain->curlib->filepath, lib->filepath) == 0) {
05508                                 printf("Fixed error in file; multiple instances of lib:\n %s\n", lib->filepath);
05509                                 BKE_reportf(fd->reports, RPT_WARNING, "Library '%s', '%s' had multiple instances, save and reload!", lib->name, lib->filepath);
05510 
05511                                 change_idid_adr(&fd->mainlist, fd, lib, newmain->curlib);
05512 //                              change_idid_adr_fd(fd, lib, newmain->curlib);
05513                                 
05514                                 BLI_remlink(&main->library, lib);
05515                                 MEM_freeN(lib);
05516 
05517 
05518                                 return;
05519                         }
05520                 }
05521         }
05522         /* make sure we have full path in lib->filename */
05523         BLI_strncpy(lib->filepath, lib->name, sizeof(lib->name));
05524         cleanup_path(fd->relabase, lib->filepath);
05525         
05526 //      printf("direct_link_library: name %s\n", lib->name);
05527 //      printf("direct_link_library: filename %s\n", lib->filename);
05528         
05529         /* new main */
05530         newmain= MEM_callocN(sizeof(Main), "directlink");
05531         BLI_addtail(&fd->mainlist, newmain);
05532         newmain->curlib= lib;
05533 
05534         lib->parent= NULL;
05535 }
05536 
05537 static void lib_link_library(FileData *UNUSED(fd), Main *main)
05538 {
05539         Library *lib;
05540         for(lib= main->library.first; lib; lib= lib->id.next) {
05541                 lib->id.us= 1;
05542         }
05543 }
05544 
05545 /* Always call this once you have loaded new library data to set the relative paths correctly in relation to the blend file */
05546 static void fix_relpaths_library(const char *basepath, Main *main)
05547 {
05548         Library *lib;
05549         /* BLO_read_from_memory uses a blank filename */
05550         if (basepath==NULL || basepath[0] == '\0') {
05551                 for(lib= main->library.first; lib; lib= lib->id.next) {
05552                         /* when loading a linked lib into a file which has not been saved,
05553                          * there is nothing we can be relative to, so instead we need to make
05554                          * it absolute. This can happen when appending an object with a relative
05555                          * link into an unsaved blend file. See [#27405].
05556                          * The remap relative option will make it relative again on save - campbell */
05557                         if (strncmp(lib->name, "//", 2)==0) {
05558                                 strncpy(lib->name, lib->filepath, sizeof(lib->name));
05559                         }
05560                 }
05561         }
05562         else {
05563                 for(lib= main->library.first; lib; lib= lib->id.next) {
05564                         /* Libraries store both relative and abs paths, recreate relative paths,
05565                          * relative to the blend file since indirectly linked libs will be relative to their direct linked library */
05566                         if (strncmp(lib->name, "//", 2)==0) { /* if this is relative to begin with? */
05567                                 strncpy(lib->name, lib->filepath, sizeof(lib->name));
05568                                 BLI_path_rel(lib->name, basepath);
05569                         }
05570                 }
05571         }
05572 }
05573 
05574 /* ************** READ SOUND ******************* */
05575 
05576 static void direct_link_sound(FileData *fd, bSound *sound)
05577 {
05578         sound->handle = NULL;
05579         sound->playback_handle = NULL;
05580 
05581         sound->packedfile = direct_link_packedfile(fd, sound->packedfile);
05582         sound->newpackedfile = direct_link_packedfile(fd, sound->newpackedfile);
05583 }
05584 
05585 static void lib_link_sound(FileData *fd, Main *main)
05586 {
05587         bSound *sound;
05588 
05589         sound= main->sound.first;
05590         while(sound) {
05591                 if(sound->id.flag & LIB_NEEDLINK) {
05592                         sound->id.flag -= LIB_NEEDLINK;
05593                         sound->ipo= newlibadr_us(fd, sound->id.lib, sound->ipo); // XXX depreceated - old animation system
05594                         
05595                         sound_load(main, sound);
05596 
05597                         if(sound->cache)
05598                                 sound_cache(sound, 1);
05599                 }
05600                 sound= sound->id.next;
05601         }
05602 }
05603 /* ***************** READ GROUP *************** */
05604 
05605 static void direct_link_group(FileData *fd, Group *group)
05606 {
05607         link_list(fd, &group->gobject);
05608 }
05609 
05610 static void lib_link_group(FileData *fd, Main *main)
05611 {
05612         Group *group= main->group.first;
05613         GroupObject *go;
05614         int add_us;
05615         
05616         while(group) {
05617                 if(group->id.flag & LIB_NEEDLINK) {
05618                         group->id.flag -= LIB_NEEDLINK;
05619                         
05620                         add_us= 0;
05621                         
05622                         go= group->gobject.first;
05623                         while(go) {
05624                                 go->ob= newlibadr(fd, group->id.lib, go->ob);
05625                                 if(go->ob) {
05626                                         go->ob->flag |= OB_FROMGROUP;
05627                                         /* if group has an object, it increments user... */
05628                                         add_us= 1;
05629                                         if(go->ob->id.us==0) 
05630                                                 go->ob->id.us= 1;
05631                                 }
05632                                 go= go->next;
05633                         }
05634                         if(add_us) group->id.us++;
05635                         rem_from_group(group, NULL, NULL, NULL);        /* removes NULL entries */
05636                 }
05637                 group= group->id.next;
05638         }
05639 }
05640 
05641 /* ************** GENERAL & MAIN ******************** */
05642 
05643 
05644 static const char *dataname(short id_code)
05645 {
05646         
05647         switch( id_code ) {
05648                 case ID_OB: return "Data from OB";
05649                 case ID_ME: return "Data from ME";
05650                 case ID_IP: return "Data from IP";
05651                 case ID_SCE: return "Data from SCE";
05652                 case ID_MA: return "Data from MA";
05653                 case ID_TE: return "Data from TE";
05654                 case ID_CU: return "Data from CU";
05655                 case ID_GR: return "Data from GR";
05656                 case ID_AR: return "Data from AR";
05657                 case ID_AC: return "Data from AC";
05658                 case ID_LI: return "Data from LI";
05659                 case ID_MB: return "Data from MB";
05660                 case ID_IM: return "Data from IM";
05661                 case ID_LT: return "Data from LT";
05662                 case ID_LA: return "Data from LA";
05663                 case ID_CA: return "Data from CA";
05664                 case ID_KE: return "Data from KE";
05665                 case ID_WO: return "Data from WO";
05666                 case ID_SCR: return "Data from SCR";
05667                 case ID_VF: return "Data from VF";
05668                 case ID_TXT     : return "Data from TXT";
05669                 case ID_SO: return "Data from SO";
05670                 case ID_NT: return "Data from NT";
05671                 case ID_BR: return "Data from BR";
05672                 case ID_PA: return "Data from PA";
05673                 case ID_GD: return "Data from GD";
05674         }
05675         return "Data from Lib Block";
05676         
05677 }
05678 
05679 static BHead *read_data_into_oldnewmap(FileData *fd, BHead *bhead, const char *allocname)
05680 {
05681         bhead = blo_nextbhead(fd, bhead);
05682 
05683         while(bhead && bhead->code==DATA) {
05684                 void *data;
05685 #if 0
05686                 /* XXX DUMB DEBUGGING OPTION TO GIVE NAMES for guarded malloc errors */
05687                 short *sp= fd->filesdna->structs[bhead->SDNAnr];
05688                 char *tmp= malloc(100);
05689                 allocname = fd->filesdna->types[ sp[0] ];
05690                 strcpy(tmp, allocname);
05691                 data= read_struct(fd, bhead, tmp);
05692 #else
05693                 data= read_struct(fd, bhead, allocname);
05694 #endif
05695                 
05696                 if (data) {
05697                         oldnewmap_insert(fd->datamap, bhead->old, data, 0);
05698                 }
05699 
05700                 bhead = blo_nextbhead(fd, bhead);
05701         }
05702 
05703         return bhead;
05704 }
05705 
05706 static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, int flag, ID **id_r)
05707 {
05708         /* this routine reads a libblock and its direct data. Use link functions
05709          * to connect it all
05710          */
05711 
05712         ID *id;
05713         ListBase *lb;
05714         const char *allocname;
05715         
05716         /* read libblock */
05717         id = read_struct(fd, bhead, "lib block");
05718         if (id_r)
05719                 *id_r= id;
05720         if (!id)
05721                 return blo_nextbhead(fd, bhead);
05722         
05723         oldnewmap_insert(fd->libmap, bhead->old, id, bhead->code);      /* for ID_ID check */
05724         
05725         /* do after read_struct, for dna reconstruct */
05726         if(bhead->code==ID_ID) {
05727                 lb= which_libbase(main, GS(id->name));
05728         }
05729         else {
05730                 lb= which_libbase(main, bhead->code);
05731         }
05732         
05733         BLI_addtail(lb, id);
05734 
05735         /* clear first 8 bits */
05736         id->flag= (id->flag & 0xFF00) | flag | LIB_NEEDLINK;
05737         id->lib= main->curlib;
05738         if(id->flag & LIB_FAKEUSER) id->us= 1;
05739         else id->us= 0;
05740         id->icon_id = 0;
05741         id->flag &= ~LIB_ID_RECALC;
05742 
05743         /* this case cannot be direct_linked: it's just the ID part */
05744         if(bhead->code==ID_ID) {
05745                 return blo_nextbhead(fd, bhead);
05746         }
05747 
05748         /* need a name for the mallocN, just for debugging and sane prints on leaks */
05749         allocname= dataname(GS(id->name));
05750         
05751         /* read all data into fd->datamap */
05752         bhead= read_data_into_oldnewmap(fd, bhead, allocname);
05753 
05754         /* init pointers direct data */
05755         switch( GS(id->name) ) {
05756                 case ID_WM:
05757                         direct_link_windowmanager(fd, (wmWindowManager *)id);
05758                         break;
05759                 case ID_SCR:
05760                         direct_link_screen(fd, (bScreen *)id);
05761                         break;
05762                 case ID_SCE:
05763                         direct_link_scene(fd, (Scene *)id);
05764                         break;
05765                 case ID_OB:
05766                         direct_link_object(fd, (Object *)id);
05767                         break;
05768                 case ID_ME:
05769                         direct_link_mesh(fd, (Mesh *)id);
05770                         break;
05771                 case ID_CU:
05772                         direct_link_curve(fd, (Curve *)id);
05773                         break;
05774                 case ID_MB:
05775                         direct_link_mball(fd, (MetaBall *)id);
05776                         break;
05777                 case ID_MA:
05778                         direct_link_material(fd, (Material *)id);
05779                         break;
05780                 case ID_TE:
05781                         direct_link_texture(fd, (Tex *)id);
05782                         break;
05783                 case ID_IM:
05784                         direct_link_image(fd, (Image *)id);
05785                         break;
05786                 case ID_LA:
05787                         direct_link_lamp(fd, (Lamp *)id);
05788                         break;
05789                 case ID_VF:
05790                         direct_link_vfont(fd, (VFont *)id);
05791                         break;
05792                 case ID_TXT:
05793                         direct_link_text(fd, (Text *)id);
05794                         break;
05795                 case ID_IP:
05796                         direct_link_ipo(fd, (Ipo *)id);
05797                         break;
05798                 case ID_KE:
05799                         direct_link_key(fd, (Key *)id);
05800                         break;
05801                 case ID_LT:
05802                         direct_link_latt(fd, (Lattice *)id);
05803                         break;
05804                 case ID_WO:
05805                         direct_link_world(fd, (World *)id);
05806                         break;
05807                 case ID_LI:
05808                         direct_link_library(fd, (Library *)id, main);
05809                         break;
05810                 case ID_CA:
05811                         direct_link_camera(fd, (Camera *)id);
05812                         break;
05813                 case ID_SO:
05814                         direct_link_sound(fd, (bSound *)id);
05815                         break;
05816                 case ID_GR:
05817                         direct_link_group(fd, (Group *)id);
05818                         break;
05819                 case ID_AR:
05820                         direct_link_armature(fd, (bArmature*)id);
05821                         break;
05822                 case ID_AC:
05823                         direct_link_action(fd, (bAction*)id);
05824                         break;
05825                 case ID_NT:
05826                         direct_link_nodetree(fd, (bNodeTree*)id);
05827                         break;
05828                 case ID_BR:
05829                         direct_link_brush(fd, (Brush*)id);
05830                         break;
05831                 case ID_PA:
05832                         direct_link_particlesettings(fd, (ParticleSettings*)id);
05833                         break;
05834                 case ID_SCRIPT:
05835                         direct_link_script(fd, (Script*)id);
05836                         break;
05837                 case ID_GD:
05838                         direct_link_gpencil(fd, (bGPdata *)id);
05839                         break;
05840         }
05841         
05842         /*link direct data of ID properties*/
05843         if (id->properties) {
05844                 id->properties = newdataadr(fd, id->properties);
05845                 if (id->properties) { /* this case means the data was written incorrectly, it should not happen */
05846                         IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
05847                 }
05848         }
05849 
05850         oldnewmap_free_unused(fd->datamap);
05851         oldnewmap_clear(fd->datamap);
05852 
05853         return (bhead);
05854 }
05855 
05856 /* note, this has to be kept for reading older files... */
05857 /* also version info is written here */
05858 static BHead *read_global(BlendFileData *bfd, FileData *fd, BHead *bhead)
05859 {
05860         FileGlobal *fg= read_struct(fd, bhead, "Global");
05861         
05862         /* copy to bfd handle */
05863         bfd->main->subversionfile= fg->subversion;
05864         bfd->main->minversionfile= fg->minversion;
05865         bfd->main->minsubversionfile= fg->minsubversion;
05866         bfd->main->revision= fg->revision;
05867         
05868         bfd->winpos= fg->winpos;
05869         bfd->fileflags= fg->fileflags;
05870         bfd->displaymode= fg->displaymode;
05871         bfd->globalf= fg->globalf;
05872         BLI_strncpy(bfd->filename, fg->filename, sizeof(bfd->filename));
05873         
05874         if(G.fileflags & G_FILE_RECOVER)
05875                 BLI_strncpy(fd->relabase, fg->filename, sizeof(fd->relabase));
05876         
05877         bfd->curscreen= fg->curscreen;
05878         bfd->curscene= fg->curscene;
05879         
05880         MEM_freeN(fg);
05881 
05882         fd->globalf= bfd->globalf;
05883         fd->fileflags= bfd->fileflags;
05884         
05885         return blo_nextbhead(fd, bhead);
05886 }
05887 
05888 /* note, this has to be kept for reading older files... */
05889 static void link_global(FileData *fd, BlendFileData *bfd)
05890 {
05891         
05892         bfd->curscreen= newlibadr(fd, NULL, bfd->curscreen);
05893         bfd->curscene= newlibadr(fd, NULL, bfd->curscene);
05894         // this happens in files older than 2.35
05895         if(bfd->curscene==NULL) {
05896                 if(bfd->curscreen) bfd->curscene= bfd->curscreen->scene;
05897         }
05898 }
05899 
05900 static void vcol_to_fcol(Mesh *me)
05901 {
05902         MFace *mface;
05903         unsigned int *mcol, *mcoln, *mcolmain;
05904         int a;
05905 
05906         if(me->totface==0 || me->mcol==NULL) return;
05907 
05908         mcoln= mcolmain= MEM_mallocN(4*sizeof(int)*me->totface, "mcoln");
05909         mcol = (unsigned int *)me->mcol;
05910         mface= me->mface;
05911         for(a=me->totface; a>0; a--, mface++) {
05912                 mcoln[0]= mcol[mface->v1];
05913                 mcoln[1]= mcol[mface->v2];
05914                 mcoln[2]= mcol[mface->v3];
05915                 mcoln[3]= mcol[mface->v4];
05916                 mcoln+= 4;
05917         }
05918 
05919         MEM_freeN(me->mcol);
05920         me->mcol= (MCol *)mcolmain;
05921 }
05922 
05923 static int map_223_keybd_code_to_224_keybd_code(int code)
05924 {
05925         switch (code) {
05926                 case 312:       return 311; /* F12KEY */
05927                 case 159:       return 161; /* PADSLASHKEY */
05928                 case 161:       return 150; /* PAD0 */
05929                 case 154:       return 151; /* PAD1 */
05930                 case 150:       return 152; /* PAD2 */
05931                 case 155:       return 153; /* PAD3 */
05932                 case 151:       return 154; /* PAD4 */
05933                 case 156:       return 155; /* PAD5 */
05934                 case 152:       return 156; /* PAD6 */
05935                 case 157:       return 157; /* PAD7 */
05936                 case 153:       return 158; /* PAD8 */
05937                 case 158:       return 159; /* PAD9 */
05938                 default: return code;
05939         }
05940 }
05941 
05942 static void do_version_bone_head_tail_237(Bone *bone)
05943 {
05944         Bone *child;
05945         float vec[3];
05946 
05947         /* head */
05948         copy_v3_v3(bone->arm_head, bone->arm_mat[3]);
05949 
05950         /* tail is in current local coord system */
05951         copy_v3_v3(vec, bone->arm_mat[1]);
05952         mul_v3_fl(vec, bone->length);
05953         add_v3_v3v3(bone->arm_tail, bone->arm_head, vec);
05954 
05955         for(child= bone->childbase.first; child; child= child->next)
05956                 do_version_bone_head_tail_237(child);
05957 }
05958 
05959 static void bone_version_238(ListBase *lb)
05960 {
05961         Bone *bone;
05962         
05963         for(bone= lb->first; bone; bone= bone->next) {
05964                 if(bone->rad_tail==0.0f && bone->rad_head==0.0f) {
05965                         bone->rad_head= 0.25f*bone->length;
05966                         bone->rad_tail= 0.1f*bone->length;
05967                         
05968                         bone->dist-= bone->rad_head;
05969                         if(bone->dist<=0.0f) bone->dist= 0.0f;
05970                 }
05971                 bone_version_238(&bone->childbase);
05972         }
05973 }
05974 
05975 static void bone_version_239(ListBase *lb)
05976 {
05977         Bone *bone;
05978         
05979         for(bone= lb->first; bone; bone= bone->next) {
05980                 if(bone->layer==0) 
05981                         bone->layer= 1;
05982                 bone_version_239(&bone->childbase);
05983         }
05984 }
05985 
05986 static void ntree_version_241(bNodeTree *ntree)
05987 {
05988         bNode *node;
05989         
05990         if(ntree->type==NTREE_COMPOSIT) {
05991                 for(node= ntree->nodes.first; node; node= node->next) {
05992                         if(node->type==CMP_NODE_BLUR) {
05993                                 if(node->storage==NULL) {
05994                                         NodeBlurData *nbd= MEM_callocN(sizeof(NodeBlurData), "node blur patch");
05995                                         nbd->sizex= node->custom1;
05996                                         nbd->sizey= node->custom2;
05997                                         nbd->filtertype= R_FILTER_QUAD;
05998                                         node->storage= nbd;
05999                                 }
06000                         }
06001                         else if(node->type==CMP_NODE_VECBLUR) {
06002                                 if(node->storage==NULL) {
06003                                         NodeBlurData *nbd= MEM_callocN(sizeof(NodeBlurData), "node blur patch");
06004                                         nbd->samples= node->custom1;
06005                                         nbd->maxspeed= node->custom2;
06006                                         nbd->fac= 1.0f;
06007                                         node->storage= nbd;
06008                                 }
06009                         }
06010                 }
06011         }
06012 }
06013 
06014 static void ntree_version_242(bNodeTree *ntree)
06015 {
06016         bNode *node;
06017         
06018         if(ntree->type==NTREE_COMPOSIT) {
06019                 for(node= ntree->nodes.first; node; node= node->next) {
06020                         if(node->type==CMP_NODE_HUE_SAT) {
06021                                 if(node->storage) {
06022                                         NodeHueSat *nhs= node->storage;
06023                                         if(nhs->val==0.0f) nhs->val= 1.0f;
06024                                 }
06025                         }
06026                 }
06027         }
06028         else if(ntree->type==NTREE_SHADER) {
06029                 for(node= ntree->nodes.first; node; node= node->next)
06030                         if(node->type == SH_NODE_GEOMETRY && node->storage == NULL)
06031                                 node->storage= MEM_callocN(sizeof(NodeGeometry), "NodeGeometry");
06032         }
06033         
06034 }
06035 
06036 
06037 /* somehow, probably importing via python, keyblock adrcodes are not in order */
06038 static void sort_shape_fix(Main *main)
06039 {
06040         Key *key;
06041         KeyBlock *kb;
06042         int sorted= 0;
06043         
06044         while(sorted==0) {
06045                 sorted= 1;
06046                 for(key= main->key.first; key; key= key->id.next) {
06047                         for(kb= key->block.first; kb; kb= kb->next) {
06048                                 if(kb->next && kb->adrcode>kb->next->adrcode) {
06049                                         KeyBlock *next= kb->next;
06050                                         BLI_remlink(&key->block, kb);
06051                                         BLI_insertlink(&key->block, next, kb);
06052                                         kb= next;
06053                                         sorted= 0;
06054                                 }
06055                         }
06056                 }
06057                 if(sorted==0) printf("warning, shape keys were sorted incorrect, fixed it!\n");
06058         }
06059 }
06060 
06061 static void customdata_version_242(Mesh *me)
06062 {
06063         CustomDataLayer *layer;
06064         MTFace *mtf;
06065         MCol *mcol;
06066         TFace *tf;
06067         int a, mtfacen, mcoln;
06068 
06069         if (!me->vdata.totlayer) {
06070                 CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, me->mvert, me->totvert);
06071 
06072                 if (me->msticky)
06073                         CustomData_add_layer(&me->vdata, CD_MSTICKY, CD_ASSIGN, me->msticky, me->totvert);
06074                 if (me->dvert)
06075                         CustomData_add_layer(&me->vdata, CD_MDEFORMVERT, CD_ASSIGN, me->dvert, me->totvert);
06076         }
06077 
06078         if (!me->edata.totlayer)
06079                 CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, me->medge, me->totedge);
06080         
06081         if (!me->fdata.totlayer) {
06082                 CustomData_add_layer(&me->fdata, CD_MFACE, CD_ASSIGN, me->mface, me->totface);
06083 
06084                 if (me->tface) {
06085                         if (me->mcol)
06086                                 MEM_freeN(me->mcol);
06087 
06088                         me->mcol= CustomData_add_layer(&me->fdata, CD_MCOL, CD_CALLOC, NULL, me->totface);
06089                         me->mtface= CustomData_add_layer(&me->fdata, CD_MTFACE, CD_CALLOC, NULL, me->totface);
06090 
06091                         mtf= me->mtface;
06092                         mcol= me->mcol;
06093                         tf= me->tface;
06094 
06095                         for (a=0; a < me->totface; a++, mtf++, tf++, mcol+=4) {
06096                                 memcpy(mcol, tf->col, sizeof(tf->col));
06097                                 memcpy(mtf->uv, tf->uv, sizeof(tf->uv));
06098 
06099                                 mtf->flag= tf->flag;
06100                                 mtf->unwrap= tf->unwrap;
06101                                 mtf->mode= tf->mode;
06102                                 mtf->tile= tf->tile;
06103                                 mtf->tpage= tf->tpage;
06104                                 mtf->transp= tf->transp;
06105                         }
06106 
06107                         MEM_freeN(me->tface);
06108                         me->tface= NULL;
06109                 }
06110                 else if (me->mcol) {
06111                         me->mcol= CustomData_add_layer(&me->fdata, CD_MCOL, CD_ASSIGN, me->mcol, me->totface);
06112                 }
06113         }
06114 
06115         if (me->tface) {
06116                 MEM_freeN(me->tface);
06117                 me->tface= NULL;
06118         }
06119 
06120         for (a=0, mtfacen=0, mcoln=0; a < me->fdata.totlayer; a++) {
06121                 layer= &me->fdata.layers[a];
06122 
06123                 if (layer->type == CD_MTFACE) {
06124                         if (layer->name[0] == 0) {
06125                                 if (mtfacen == 0) strcpy(layer->name, "UVTex");
06126                                 else sprintf(layer->name, "UVTex.%.3d", mtfacen);
06127                         }
06128                         mtfacen++;
06129                 }
06130                 else if (layer->type == CD_MCOL) {
06131                         if (layer->name[0] == 0) {
06132                                 if (mcoln == 0) strcpy(layer->name, "Col");
06133                                 else sprintf(layer->name, "Col.%.3d", mcoln);
06134                         }
06135                         mcoln++;
06136                 }
06137         }
06138 
06139         mesh_update_customdata_pointers(me);
06140 }
06141 
06142 /*only copy render texface layer from active*/
06143 static void customdata_version_243(Mesh *me)
06144 {
06145         CustomDataLayer *layer;
06146         int a;
06147 
06148         for (a=0; a < me->fdata.totlayer; a++) {
06149                 layer= &me->fdata.layers[a];
06150                 layer->active_rnd = layer->active;
06151         }
06152 }
06153 
06154 /* struct NodeImageAnim moved to ImageUser, and we make it default available */
06155 static void do_version_ntree_242_2(bNodeTree *ntree)
06156 {
06157         bNode *node;
06158         
06159         if(ntree->type==NTREE_COMPOSIT) {
06160                 for(node= ntree->nodes.first; node; node= node->next) {
06161                         if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
06162                                 /* only image had storage */
06163                                 if(node->storage) {
06164                                         NodeImageAnim *nia= node->storage;
06165                                         ImageUser *iuser= MEM_callocN(sizeof(ImageUser), "ima user node");
06166 
06167                                         iuser->frames= nia->frames;
06168                                         iuser->sfra= nia->sfra;
06169                                         iuser->offset= nia->nr-1;
06170                                         iuser->cycl= nia->cyclic;
06171                                         iuser->fie_ima= 2;
06172                                         iuser->ok= 1;
06173                                         
06174                                         node->storage= iuser;
06175                                         MEM_freeN(nia);
06176                                 }
06177                                 else {
06178                                         ImageUser *iuser= node->storage= MEM_callocN(sizeof(ImageUser), "node image user");
06179                                         iuser->sfra= 1;
06180                                         iuser->fie_ima= 2;
06181                                         iuser->ok= 1;
06182                                 }
06183                         }
06184                 }
06185         }
06186 }
06187 
06188 static void ntree_version_245(FileData *fd, Library *lib, bNodeTree *ntree)
06189 {
06190         bNode *node;
06191         NodeTwoFloats *ntf;
06192         ID *nodeid;
06193         Image *image;
06194         ImageUser *iuser;
06195 
06196         if(ntree->type==NTREE_COMPOSIT) {
06197                 for(node= ntree->nodes.first; node; node= node->next) {
06198                         if(node->type == CMP_NODE_ALPHAOVER) {
06199                                 if(!node->storage) {
06200                                         ntf= MEM_callocN(sizeof(NodeTwoFloats), "NodeTwoFloats");
06201                                         node->storage= ntf;
06202                                         if(node->custom1)
06203                                                 ntf->x= 1.0f;
06204                                 }
06205                         }
06206                         
06207                         /* fix for temporary flag changes during 245 cycle */
06208                         nodeid= newlibadr(fd, lib, node->id);
06209                         if(node->storage && nodeid && GS(nodeid->name) == ID_IM) {
06210                                 image= (Image*)nodeid;
06211                                 iuser= node->storage;
06212                                 if(iuser->flag & IMA_OLD_PREMUL) {
06213                                         iuser->flag &= ~IMA_OLD_PREMUL;
06214                                         iuser->flag |= IMA_DO_PREMUL;
06215                                 }
06216                                 if(iuser->flag & IMA_DO_PREMUL) {
06217                                         image->flag &= ~IMA_OLD_PREMUL;
06218                                         image->flag |= IMA_DO_PREMUL;
06219                                 }
06220                         }
06221                 }
06222         }
06223 }
06224 
06225 static void idproperties_fix_groups_lengths_recurse(IDProperty *prop)
06226 {
06227         IDProperty *loop;
06228         int i;
06229         
06230         for (loop=prop->data.group.first, i=0; loop; loop=loop->next, i++) {
06231                 if (loop->type == IDP_GROUP) idproperties_fix_groups_lengths_recurse(loop);
06232         }
06233         
06234         if (prop->len != i) {
06235                 printf("Found and fixed bad id property group length.\n");
06236                 prop->len = i;
06237         }
06238 }
06239 
06240 static void idproperties_fix_group_lengths(ListBase idlist)
06241 {
06242         ID *id;
06243         
06244         for (id=idlist.first; id; id=id->next) {
06245                 if (id->properties) {
06246                         idproperties_fix_groups_lengths_recurse(id->properties);
06247                 }
06248         }
06249 }
06250 
06251 static void alphasort_version_246(FileData *fd, Library *lib, Mesh *me)
06252 {
06253         Material *ma;
06254         MFace *mf;
06255         MTFace *tf;
06256         int a, b, texalpha;
06257 
06258         /* verify we have a tface layer */
06259         for(b=0; b<me->fdata.totlayer; b++)
06260                 if(me->fdata.layers[b].type == CD_MTFACE)
06261                         break;
06262         
06263         if(b == me->fdata.totlayer)
06264                 return;
06265 
06266         /* if we do, set alpha sort if the game engine did it before */
06267         for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
06268                 if(mf->mat_nr < me->totcol) {
06269                         ma= newlibadr(fd, lib, me->mat[(int)mf->mat_nr]);
06270                         texalpha = 0;
06271 
06272                         /* we can't read from this if it comes from a library,
06273                          * because direct_link might not have happened on it,
06274                          * so ma->mtex is not pointing to valid memory yet */
06275                         if(ma && ma->id.lib)
06276                                 ma= NULL;
06277 
06278                         for(b=0; ma && b<MAX_MTEX; b++)
06279                                 if(ma->mtex && ma->mtex[b] && ma->mtex[b]->mapto & MAP_ALPHA)
06280                                         texalpha = 1;
06281                 }
06282                 else {
06283                         ma= NULL;
06284                         texalpha = 0;
06285                 }
06286 
06287                 for(b=0; b<me->fdata.totlayer; b++) {
06288                         if(me->fdata.layers[b].type == CD_MTFACE) {
06289                                 tf = ((MTFace*)me->fdata.layers[b].data) + a;
06290 
06291                                 tf->mode &= ~TF_ALPHASORT;
06292                                 if(ma && (ma->mode & MA_ZTRANSP))
06293                                         if(ELEM(tf->transp, TF_ALPHA, TF_ADD) || (texalpha && (tf->transp != TF_CLIP)))
06294                                                 tf->mode |= TF_ALPHASORT;
06295                         }
06296                 }
06297         }
06298 }
06299 
06300 /* 2.50 patch */
06301 static void area_add_header_region(ScrArea *sa, ListBase *lb)
06302 {
06303         ARegion *ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06304         
06305         BLI_addtail(lb, ar);
06306         ar->regiontype= RGN_TYPE_HEADER;
06307         if(sa->headertype==HEADERDOWN)
06308                 ar->alignment= RGN_ALIGN_BOTTOM;
06309         else
06310                 ar->alignment= RGN_ALIGN_TOP;
06311         
06312         /* initialise view2d data for header region, to allow panning */
06313         /* is copy from ui_view2d.c */
06314         ar->v2d.keepzoom = (V2D_LOCKZOOM_X|V2D_LOCKZOOM_Y|V2D_LIMITZOOM|V2D_KEEPASPECT);
06315         ar->v2d.keepofs = V2D_LOCKOFS_Y;
06316         ar->v2d.keeptot = V2D_KEEPTOT_STRICT; 
06317         ar->v2d.align = V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_NEG_Y;
06318         ar->v2d.flag = (V2D_PIXELOFS_X|V2D_PIXELOFS_Y);
06319 }
06320 
06321 static void sequencer_init_preview_region(ARegion* ar)
06322 {
06323         // XXX a bit ugly still, copied from space_sequencer
06324         /* NOTE: if you change values here, also change them in space_sequencer.c, sequencer_new */
06325         ar->regiontype= RGN_TYPE_PREVIEW;
06326         ar->alignment= RGN_ALIGN_TOP;
06327         ar->flag |= RGN_FLAG_HIDDEN;
06328         ar->v2d.keepzoom= V2D_KEEPASPECT | V2D_KEEPZOOM;
06329         ar->v2d.minzoom= 0.00001f;
06330         ar->v2d.maxzoom= 100000.0f;
06331         ar->v2d.tot.xmin= -960.0f; /* 1920 width centered */
06332         ar->v2d.tot.ymin= -540.0f; /* 1080 height centered */
06333         ar->v2d.tot.xmax= 960.0f;
06334         ar->v2d.tot.ymax= 540.0f;
06335         ar->v2d.min[0]= 0.0f;
06336         ar->v2d.min[1]= 0.0f;
06337         ar->v2d.max[0]= 12000.0f;
06338         ar->v2d.max[1]= 12000.0f;
06339         ar->v2d.cur= ar->v2d.tot;
06340         ar->v2d.align= V2D_ALIGN_FREE; // (V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_NEG_Y);
06341         ar->v2d.keeptot= V2D_KEEPTOT_FREE;
06342 }
06343 
06344 /* 2.50 patch */
06345 static void area_add_window_regions(ScrArea *sa, SpaceLink *sl, ListBase *lb)
06346 {
06347         ARegion *ar;
06348         ARegion *ar_main;
06349 
06350         if(sl) {
06351                 /* first channels for ipo action nla... */
06352                 switch(sl->spacetype) {
06353                         case SPACE_IPO:
06354                                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06355                                 BLI_addtail(lb, ar);
06356                                 ar->regiontype= RGN_TYPE_CHANNELS;
06357                                 ar->alignment= RGN_ALIGN_LEFT; 
06358                                 ar->v2d.scroll= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM);
06359                                 
06360                                         // for some reason, this doesn't seem to go auto like for NLA...
06361                                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06362                                 BLI_addtail(lb, ar);
06363                                 ar->regiontype= RGN_TYPE_UI;
06364                                 ar->alignment= RGN_ALIGN_RIGHT;
06365                                 ar->v2d.scroll= V2D_SCROLL_RIGHT;
06366                                 ar->v2d.flag = RGN_FLAG_HIDDEN;
06367                                 break;
06368                                 
06369                         case SPACE_ACTION:
06370                                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06371                                 BLI_addtail(lb, ar);
06372                                 ar->regiontype= RGN_TYPE_CHANNELS;
06373                                 ar->alignment= RGN_ALIGN_LEFT;
06374                                 ar->v2d.scroll= V2D_SCROLL_BOTTOM;
06375                                 ar->v2d.flag = V2D_VIEWSYNC_AREA_VERTICAL;
06376                                 break;
06377                                 
06378                         case SPACE_NLA:
06379                                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06380                                 BLI_addtail(lb, ar);
06381                                 ar->regiontype= RGN_TYPE_CHANNELS;
06382                                 ar->alignment= RGN_ALIGN_LEFT;
06383                                 ar->v2d.scroll= V2D_SCROLL_BOTTOM;
06384                                 ar->v2d.flag = V2D_VIEWSYNC_AREA_VERTICAL;
06385                                 
06386                                         // for some reason, some files still don't get this auto
06387                                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06388                                 BLI_addtail(lb, ar);
06389                                 ar->regiontype= RGN_TYPE_UI;
06390                                 ar->alignment= RGN_ALIGN_RIGHT;
06391                                 ar->v2d.scroll= V2D_SCROLL_RIGHT;
06392                                 ar->v2d.flag = RGN_FLAG_HIDDEN;
06393                                 break;
06394                                 
06395                         case SPACE_NODE:
06396                                 ar= MEM_callocN(sizeof(ARegion), "nodetree area for node");
06397                                 BLI_addtail(lb, ar);
06398                                 ar->regiontype= RGN_TYPE_UI;
06399                                 ar->alignment= RGN_ALIGN_LEFT;
06400                                 ar->v2d.scroll = (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM);
06401                                 ar->v2d.flag = V2D_VIEWSYNC_AREA_VERTICAL;
06402                                 /* temporarily hide it */
06403                                 ar->flag = RGN_FLAG_HIDDEN;
06404                                 break;
06405                         case SPACE_FILE:
06406                                 ar= MEM_callocN(sizeof(ARegion), "nodetree area for node");
06407                                 BLI_addtail(lb, ar);
06408                                 ar->regiontype= RGN_TYPE_CHANNELS;
06409                                 ar->alignment= RGN_ALIGN_LEFT;
06410 
06411                                 ar= MEM_callocN(sizeof(ARegion), "ui area for file");
06412                                 BLI_addtail(lb, ar);
06413                                 ar->regiontype= RGN_TYPE_UI;
06414                                 ar->alignment= RGN_ALIGN_TOP;
06415                                 break;
06416                         case SPACE_SEQ:
06417                                 ar_main = (ARegion*)lb->first;
06418                                 for (; ar_main; ar_main = ar_main->next) {
06419                                         if (ar_main->regiontype == RGN_TYPE_WINDOW)
06420                                                 break;
06421                                 }
06422                                 ar= MEM_callocN(sizeof(ARegion), "preview area for sequencer");
06423                                 BLI_insertlinkbefore(lb, ar_main, ar);
06424                                 sequencer_init_preview_region(ar);
06425                                 break;
06426                         case SPACE_VIEW3D:
06427                                 /* toolbar */
06428                                 ar= MEM_callocN(sizeof(ARegion), "toolbar for view3d");
06429                                 
06430                                 BLI_addtail(lb, ar);
06431                                 ar->regiontype= RGN_TYPE_TOOLS;
06432                                 ar->alignment= RGN_ALIGN_LEFT;
06433                                 ar->flag = RGN_FLAG_HIDDEN;
06434                                 
06435                                 /* tool properties */
06436                                 ar= MEM_callocN(sizeof(ARegion), "tool properties for view3d");
06437                                 
06438                                 BLI_addtail(lb, ar);
06439                                 ar->regiontype= RGN_TYPE_TOOL_PROPS;
06440                                 ar->alignment= RGN_ALIGN_BOTTOM|RGN_SPLIT_PREV;
06441                                 ar->flag = RGN_FLAG_HIDDEN;
06442                                 
06443                                 /* buttons/list view */
06444                                 ar= MEM_callocN(sizeof(ARegion), "buttons for view3d");
06445                                 
06446                                 BLI_addtail(lb, ar);
06447                                 ar->regiontype= RGN_TYPE_UI;
06448                                 ar->alignment= RGN_ALIGN_RIGHT;
06449                                 ar->flag = RGN_FLAG_HIDDEN;
06450 #if 0
06451                         case SPACE_BUTS:
06452                                 /* context UI region */
06453                                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06454                                 BLI_addtail(lb, ar);
06455                                 ar->regiontype= RGN_TYPE_UI;
06456                                 ar->alignment= RGN_ALIGN_RIGHT;
06457                                 
06458                                 break;
06459 #endif
06460                 }
06461         }
06462 
06463         /* main region */
06464         ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06465         
06466         BLI_addtail(lb, ar);
06467         ar->winrct= sa->totrct;
06468         
06469         ar->regiontype= RGN_TYPE_WINDOW;
06470         
06471         if(sl) {
06472                 /* if active spacetype has view2d data, copy that over to main region */
06473                 /* and we split view3d */
06474                 switch(sl->spacetype) {
06475                         case SPACE_VIEW3D:
06476                                 view3d_split_250((View3D *)sl, lb);
06477                                 break;          
06478                                                 
06479                         case SPACE_OUTLINER:
06480                         {
06481                                 SpaceOops *soops= (SpaceOops *)sl;
06482                                 
06483                                 memcpy(&ar->v2d, &soops->v2d, sizeof(View2D));
06484                                 
06485                                 ar->v2d.scroll &= ~V2D_SCROLL_LEFT;
06486                                 ar->v2d.scroll |= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM_O);
06487                                 ar->v2d.align = (V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_POS_Y);
06488                                 ar->v2d.keepzoom |= (V2D_LOCKZOOM_X|V2D_LOCKZOOM_Y|V2D_KEEPASPECT);
06489                                 ar->v2d.keeptot = V2D_KEEPTOT_STRICT;
06490                                 ar->v2d.minzoom= ar->v2d.maxzoom= 1.0f;
06491                                 //ar->v2d.flag |= V2D_IS_INITIALISED;
06492                         }
06493                                 break;
06494                         case SPACE_TIME:
06495                         {
06496                                 SpaceTime *stime= (SpaceTime *)sl;
06497                                 memcpy(&ar->v2d, &stime->v2d, sizeof(View2D));
06498                                 
06499                                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06500                                 ar->v2d.align |= V2D_ALIGN_NO_NEG_Y;
06501                                 ar->v2d.keepofs |= V2D_LOCKOFS_Y;
06502                                 ar->v2d.keepzoom |= V2D_LOCKZOOM_Y;
06503                                 ar->v2d.tot.ymin= ar->v2d.cur.ymin= -10.0;
06504                                 ar->v2d.min[1]= ar->v2d.max[1]= 20.0;
06505                         }
06506                                 break;
06507                         case SPACE_IPO:
06508                         {
06509                                 SpaceIpo *sipo= (SpaceIpo *)sl;
06510                                 memcpy(&ar->v2d, &sipo->v2d, sizeof(View2D));
06511                                 
06512                                 /* init mainarea view2d */
06513                                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06514                                 ar->v2d.scroll |= (V2D_SCROLL_LEFT|V2D_SCROLL_SCALE_VERTICAL);
06515                                 
06516                                 ar->v2d.min[0]= FLT_MIN;
06517                                 ar->v2d.min[1]= FLT_MIN;
06518                                 
06519                                 ar->v2d.max[0]= MAXFRAMEF;
06520                                 ar->v2d.max[1]= FLT_MAX;
06521                                 
06522                                 //ar->v2d.flag |= V2D_IS_INITIALISED;
06523                                 break;
06524                         }
06525                         case SPACE_SOUND:
06526                         {
06527                                 SpaceSound *ssound= (SpaceSound *)sl;
06528                                 memcpy(&ar->v2d, &ssound->v2d, sizeof(View2D));
06529                                 
06530                                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06531                                 ar->v2d.scroll |= (V2D_SCROLL_LEFT);
06532                                 //ar->v2d.flag |= V2D_IS_INITIALISED;
06533                                 break;
06534                         }
06535                         case SPACE_NLA:
06536                         {
06537                                 SpaceNla *snla= (SpaceNla *)sl;
06538                                 memcpy(&ar->v2d, &snla->v2d, sizeof(View2D));
06539                                 
06540                                 ar->v2d.tot.ymin= (float)(-sa->winy)/3.0f;
06541                                 ar->v2d.tot.ymax= 0.0f;
06542                                 
06543                                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06544                                 ar->v2d.scroll |= (V2D_SCROLL_RIGHT);
06545                                 ar->v2d.align = V2D_ALIGN_NO_POS_Y;
06546                                 ar->v2d.flag |= V2D_VIEWSYNC_AREA_VERTICAL;
06547                                 break;
06548                         }
06549                         case SPACE_ACTION:
06550                         {
06551                                 SpaceAction *saction= (SpaceAction *)sl;
06552                                 
06553                                 /* we totally reinit the view for the Action Editor, as some old instances had some weird cruft set */
06554                                 ar->v2d.tot.xmin= -20.0f;
06555                                 ar->v2d.tot.ymin= (float)(-sa->winy)/3.0f;
06556                                 ar->v2d.tot.xmax= (float)((sa->winx > 120)? (sa->winx) : 120);
06557                                 ar->v2d.tot.ymax= 0.0f;
06558                                 
06559                                 ar->v2d.cur= ar->v2d.tot;
06560                                 
06561                                 ar->v2d.min[0]= 0.0f;
06562                                 ar->v2d.min[1]= 0.0f;
06563                                 
06564                                 ar->v2d.max[0]= MAXFRAMEF;
06565                                 ar->v2d.max[1]= FLT_MAX;
06566 
06567                                 ar->v2d.minzoom= 0.01f;
06568                                 ar->v2d.maxzoom= 50;
06569                                 ar->v2d.scroll = (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06570                                 ar->v2d.scroll |= (V2D_SCROLL_RIGHT);
06571                                 ar->v2d.keepzoom= V2D_LOCKZOOM_Y;
06572                                 ar->v2d.align= V2D_ALIGN_NO_POS_Y;
06573                                 ar->v2d.flag = V2D_VIEWSYNC_AREA_VERTICAL;
06574                                 
06575                                 /* for old files with ShapeKey editors open + an action set, clear the action as 
06576                                  * it doesn't make sense in the new system (i.e. violates concept that ShapeKey edit
06577                                  * only shows ShapeKey-rooted actions only)
06578                                  */
06579                                 if (saction->mode == SACTCONT_SHAPEKEY)
06580                                         saction->action = NULL;
06581                                 break;
06582                         }
06583                         case SPACE_SEQ:
06584                         {
06585                                 SpaceSeq *sseq= (SpaceSeq *)sl;
06586                                 memcpy(&ar->v2d, &sseq->v2d, sizeof(View2D));
06587                                 
06588                                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06589                                 ar->v2d.scroll |= (V2D_SCROLL_LEFT|V2D_SCROLL_SCALE_VERTICAL);
06590                                 ar->v2d.align= V2D_ALIGN_NO_NEG_Y;
06591                                 ar->v2d.flag |= V2D_IS_INITIALISED;
06592                                 break;
06593                         }
06594                         case SPACE_NODE:
06595                         {
06596                                 SpaceNode *snode= (SpaceNode *)sl;
06597                                 memcpy(&ar->v2d, &snode->v2d, sizeof(View2D));
06598                                 
06599                                 ar->v2d.scroll= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM);
06600                                 ar->v2d.keepzoom= V2D_LIMITZOOM|V2D_KEEPASPECT;
06601                                 break;
06602                         }
06603                         case SPACE_BUTS:
06604                         {
06605                                 SpaceButs *sbuts= (SpaceButs *)sl;
06606                                 memcpy(&ar->v2d, &sbuts->v2d, sizeof(View2D));
06607                                 
06608                                 ar->v2d.scroll |= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM); 
06609                                 break;
06610                         }
06611                         case SPACE_FILE:
06612                          {
06613                                 // SpaceFile *sfile= (SpaceFile *)sl;
06614                                 ar->v2d.tot.xmin = ar->v2d.tot.ymin = 0;
06615                                 ar->v2d.tot.xmax = ar->winx;
06616                                 ar->v2d.tot.ymax = ar->winy;
06617                                 ar->v2d.cur = ar->v2d.tot;
06618                                 ar->regiontype= RGN_TYPE_WINDOW;
06619                                 ar->v2d.scroll = (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM_O);
06620                                 ar->v2d.align = (V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_POS_Y);
06621                                 ar->v2d.keepzoom = (V2D_LOCKZOOM_X|V2D_LOCKZOOM_Y|V2D_LIMITZOOM|V2D_KEEPASPECT);
06622                                 break;
06623                         }
06624                         case SPACE_TEXT:
06625                         {
06626                                 SpaceText *st= (SpaceText *)sl;
06627                                 st->flags |= ST_FIND_WRAP;
06628                         }
06629                                 //case SPACE_XXX: // FIXME... add other ones
06630                                 //      memcpy(&ar->v2d, &((SpaceXxx *)sl)->v2d, sizeof(View2D));
06631                                 //      break;
06632                 }
06633         }
06634 }
06635 
06636 static void do_versions_windowmanager_2_50(bScreen *screen)
06637 {
06638         ScrArea *sa;
06639         SpaceLink *sl;
06640         
06641         /* add regions */
06642         for(sa= screen->areabase.first; sa; sa= sa->next) {
06643                 
06644                 /* we keep headertype variable to convert old files only */
06645                 if(sa->headertype)
06646                         area_add_header_region(sa, &sa->regionbase);
06647                 
06648                 area_add_window_regions(sa, sa->spacedata.first, &sa->regionbase);
06649                 
06650                 /* space imageselect is depricated */
06651                 for(sl= sa->spacedata.first; sl; sl= sl->next) {
06652                         if(sl->spacetype==SPACE_IMASEL)
06653                                 sl->spacetype= SPACE_INFO;      /* spacedata then matches */
06654                 }               
06655                 
06656                 /* it seems to be possible in 2.5 to have this saved, filewindow probably */
06657                 sa->butspacetype= sa->spacetype;
06658                 
06659                 /* pushed back spaces also need regions! */
06660                 if(sa->spacedata.first) {
06661                         sl= sa->spacedata.first;
06662                         for(sl= sl->next; sl; sl= sl->next) {
06663                                 if(sa->headertype)
06664                                         area_add_header_region(sa, &sl->regionbase);
06665                                 area_add_window_regions(sa, sl, &sl->regionbase);
06666                         }
06667                 }
06668         }
06669 }
06670 
06671 static void versions_gpencil_add_main(ListBase *lb, ID *id, const char *name)
06672 {
06673         
06674         BLI_addtail(lb, id);
06675         id->us= 1;
06676         id->flag= LIB_FAKEUSER;
06677         *( (short *)id->name )= ID_GD;
06678         
06679         new_id(lb, id, name);
06680         /* alphabetic insterion: is in new_id */
06681         
06682         if(G.f & G_DEBUG)
06683                 printf("Converted GPencil to ID: %s\n", id->name+2);
06684 }
06685 
06686 static void do_versions_gpencil_2_50(Main *main, bScreen *screen)
06687 {
06688         ScrArea *sa;
06689         SpaceLink *sl;
06690         
06691         /* add regions */
06692         for(sa= screen->areabase.first; sa; sa= sa->next) {
06693                 for(sl= sa->spacedata.first; sl; sl= sl->next) {
06694                         if (sl->spacetype==SPACE_VIEW3D) {
06695                                 View3D *v3d= (View3D*) sl;
06696                                 if(v3d->gpd) {
06697                                         versions_gpencil_add_main(&main->gpencil, (ID *)v3d->gpd, "GPencil View3D");
06698                                         v3d->gpd= NULL;
06699                                 }
06700                         }
06701                         else if (sl->spacetype==SPACE_NODE) {
06702                                 SpaceNode *snode= (SpaceNode *)sl;
06703                                 if(snode->gpd) {
06704                                         versions_gpencil_add_main(&main->gpencil, (ID *)snode->gpd, "GPencil Node");
06705                                         snode->gpd= NULL;
06706                                 }
06707                         }
06708                         else if (sl->spacetype==SPACE_SEQ) {
06709                                 SpaceSeq *sseq= (SpaceSeq *)sl;
06710                                 if(sseq->gpd) {
06711                                         versions_gpencil_add_main(&main->gpencil, (ID *)sseq->gpd, "GPencil Node");
06712                                         sseq->gpd= NULL;
06713                                 }
06714                         }
06715                         else if (sl->spacetype==SPACE_IMAGE) {
06716                                 SpaceImage *sima= (SpaceImage *)sl;
06717 #if 0                   /* see comment on r28002 */
06718                                 if(sima->gpd) {
06719                                         versions_gpencil_add_main(&main->gpencil, (ID *)sima->gpd, "GPencil Image");
06720                                         sima->gpd= NULL;
06721                                 }
06722 #else
06723                                 sima->gpd= NULL;
06724 #endif
06725                         }
06726                 }
06727         }               
06728 }
06729 
06730 static void do_version_mtex_factor_2_50(MTex **mtex_array, short idtype)
06731 {
06732         MTex *mtex;
06733         float varfac, colfac;
06734         int a, neg;
06735 
06736         if(!mtex_array)
06737                 return;
06738 
06739         for(a=0; a<MAX_MTEX; a++) {
06740                 if(mtex_array[a]) {
06741                         mtex= mtex_array[a];
06742 
06743                         neg= mtex->maptoneg;
06744                         varfac= mtex->varfac;
06745                         colfac= mtex->colfac;
06746 
06747                         if(neg & MAP_DISP) mtex->dispfac= -mtex->dispfac;
06748                         if(neg & MAP_NORM) mtex->norfac= -mtex->norfac;
06749                         if(neg & MAP_WARP) mtex->warpfac= -mtex->warpfac;
06750 
06751                         mtex->colspecfac= (neg & MAP_COLSPEC)? -colfac: colfac;
06752                         mtex->mirrfac= (neg & MAP_COLMIR)? -colfac: colfac;
06753                         mtex->alphafac= (neg & MAP_ALPHA)? -varfac: varfac;
06754                         mtex->difffac= (neg & MAP_REF)? -varfac: varfac;
06755                         mtex->specfac= (neg & MAP_SPEC)? -varfac: varfac;
06756                         mtex->emitfac= (neg & MAP_EMIT)? -varfac: varfac;
06757                         mtex->hardfac= (neg & MAP_HAR)? -varfac: varfac;
06758                         mtex->raymirrfac= (neg & MAP_RAYMIRR)? -varfac: varfac;
06759                         mtex->translfac= (neg & MAP_TRANSLU)? -varfac: varfac;
06760                         mtex->ambfac= (neg & MAP_AMB)? -varfac: varfac;
06761                         mtex->colemitfac= (neg & MAP_EMISSION_COL)? -colfac: colfac;
06762                         mtex->colreflfac= (neg & MAP_REFLECTION_COL)? -colfac: colfac;
06763                         mtex->coltransfac= (neg & MAP_TRANSMISSION_COL)? -colfac: colfac;
06764                         mtex->densfac= (neg & MAP_DENSITY)? -varfac: varfac;
06765                         mtex->scatterfac= (neg & MAP_SCATTERING)? -varfac: varfac;
06766                         mtex->reflfac= (neg & MAP_REFLECTION)? -varfac: varfac;
06767 
06768                         mtex->timefac= (neg & MAP_PA_TIME)? -varfac: varfac;
06769                         mtex->lengthfac= (neg & MAP_PA_LENGTH)? -varfac: varfac;
06770                         mtex->clumpfac= (neg & MAP_PA_CLUMP)? -varfac: varfac;
06771                         mtex->kinkfac= (neg & MAP_PA_KINK)? -varfac: varfac;
06772                         mtex->roughfac= (neg & MAP_PA_ROUGH)? -varfac: varfac;
06773                         mtex->padensfac= (neg & MAP_PA_DENS)? -varfac: varfac;
06774                         mtex->lifefac= (neg & MAP_PA_LIFE)? -varfac: varfac;
06775                         mtex->sizefac= (neg & MAP_PA_SIZE)? -varfac: varfac;
06776                         mtex->ivelfac= (neg & MAP_PA_IVEL)? -varfac: varfac;
06777 
06778                         mtex->shadowfac= (neg & LAMAP_SHAD)? -colfac: colfac;
06779 
06780                         mtex->zenupfac= (neg & WOMAP_ZENUP)? -colfac: colfac;
06781                         mtex->zendownfac= (neg & WOMAP_ZENDOWN)? -colfac: colfac;
06782                         mtex->blendfac= (neg & WOMAP_BLEND)? -varfac: varfac;
06783 
06784                         if(idtype == ID_MA)
06785                                 mtex->colfac= (neg & MAP_COL)? -colfac: colfac;
06786                         else if(idtype == ID_LA)
06787                                 mtex->colfac= (neg & LAMAP_COL)? -colfac: colfac;
06788                         else if(idtype == ID_WO)
06789                                 mtex->colfac= (neg & WOMAP_HORIZ)? -colfac: colfac;
06790                 }
06791         }
06792 }
06793 
06794 static void do_version_mdef_250(Main *main)
06795 {
06796         Object *ob;
06797         ModifierData *md;
06798         MeshDeformModifierData *mmd;
06799 
06800         for(ob= main->object.first; ob; ob=ob->id.next) {
06801                 for(md=ob->modifiers.first; md; md=md->next) {
06802                         if(md->type == eModifierType_MeshDeform) {
06803                                 mmd= (MeshDeformModifierData*)md;
06804 
06805                                 if(mmd->bindcos) {
06806                                         /* make bindcos NULL in order to trick older versions
06807                                            into thinking that the mesh was not bound yet */
06808                                         mmd->bindcagecos= mmd->bindcos;
06809                                         mmd->bindcos= NULL;
06810 
06811                                         modifier_mdef_compact_influences(md);
06812                                 }
06813                         }
06814                 }
06815         }
06816 }
06817 
06818 static void do_version_constraints_radians_degrees_250(ListBase *lb)
06819 {
06820         bConstraint *con;
06821 
06822         for     (con=lb->first; con; con=con->next) {
06823                 if(con->type==CONSTRAINT_TYPE_RIGIDBODYJOINT) {
06824                         bRigidBodyJointConstraint *data = con->data;
06825                         data->axX *= (float)(M_PI/180.0);
06826                         data->axY *= (float)(M_PI/180.0);
06827                         data->axZ *= (float)(M_PI/180.0);
06828                 }
06829                 else if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
06830                         bKinematicConstraint *data = con->data;
06831                         data->poleangle *= (float)(M_PI/180.0);
06832                 }
06833                 else if(con->type==CONSTRAINT_TYPE_ROTLIMIT) {
06834                         bRotLimitConstraint *data = con->data;
06835 
06836                         data->xmin *= (float)(M_PI/180.0);
06837                         data->xmax *= (float)(M_PI/180.0);
06838                         data->ymin *= (float)(M_PI/180.0);
06839                         data->ymax *= (float)(M_PI/180.0);
06840                         data->zmin *= (float)(M_PI/180.0);
06841                         data->zmax *= (float)(M_PI/180.0);
06842                 }
06843         }
06844 }
06845 
06846 /* NOTE: this version patch is intended for versions < 2.52.2, but was initially introduced in 2.27 already */
06847 static void do_version_old_trackto_to_constraints(Object *ob)
06848 {
06849         /* create new trackto constraint from the relationship */
06850         if (ob->track)
06851         {
06852                 bConstraint *con= add_ob_constraint(ob, "AutoTrack", CONSTRAINT_TYPE_TRACKTO);
06853                 bTrackToConstraint *data = con->data;
06854                 
06855                 /* copy tracking settings from the object */
06856                 data->tar = ob->track;
06857                 data->reserved1 = ob->trackflag;
06858                 data->reserved2 = ob->upflag;
06859         }
06860         
06861         /* clear old track setting */
06862         ob->track = NULL;
06863 }
06864 
06865 static void do_versions_seq_unique_name_all_strips(
06866         Scene * sce, ListBase *seqbasep)
06867 {
06868         Sequence * seq = seqbasep->first;
06869 
06870         while(seq) {
06871                 seqbase_unique_name_recursive(&sce->ed->seqbase, seq);
06872                 if (seq->seqbase.first) {
06873                         do_versions_seq_unique_name_all_strips(
06874                                 sce, &seq->seqbase);
06875                 }
06876                 seq=seq->next;
06877         }
06878 }
06879 
06880 
06881 static void do_version_bone_roll_256(Bone *bone)
06882 {
06883         Bone *child;
06884         float submat[3][3];
06885         
06886         copy_m3_m4(submat, bone->arm_mat);
06887         mat3_to_vec_roll(submat, NULL, &bone->arm_roll);
06888         
06889         for(child = bone->childbase.first; child; child = child->next)
06890                 do_version_bone_roll_256(child);
06891 }
06892 
06893 static void do_versions(FileData *fd, Library *lib, Main *main)
06894 {
06895         /* WATCH IT!!!: pointers from libdata have not been converted */
06896 
06897         if(G.f & G_DEBUG)
06898                 printf("read file %s\n  Version %d sub %d svn r%d\n", fd->relabase, main->versionfile, main->subversionfile, main->revision);
06899         
06900         if(main->versionfile == 100) {
06901                 /* tex->extend and tex->imageflag have changed: */
06902                 Tex *tex = main->tex.first;
06903                 while(tex) {
06904                         if(tex->id.flag & LIB_NEEDLINK) {
06905 
06906                                 if(tex->extend==0) {
06907                                         if(tex->xrepeat || tex->yrepeat) tex->extend= TEX_REPEAT;
06908                                         else {
06909                                                 tex->extend= TEX_EXTEND;
06910                                                 tex->xrepeat= tex->yrepeat= 1;
06911                                         }
06912                                 }
06913 
06914                         }
06915                         tex= tex->id.next;
06916                 }
06917         }
06918         if(main->versionfile <= 101) {
06919                 /* frame mapping */
06920                 Scene *sce = main->scene.first;
06921                 while(sce) {
06922                         sce->r.framapto= 100;
06923                         sce->r.images= 100;
06924                         sce->r.framelen= 1.0;
06925                         sce= sce->id.next;
06926                 }
06927         }
06928         if(main->versionfile <= 102) {
06929                 /* init halo's at 1.0 */
06930                 Material *ma = main->mat.first;
06931                 while(ma) {
06932                         ma->add= 1.0;
06933                         ma= ma->id.next;
06934                 }
06935         }
06936         if(main->versionfile <= 103) {
06937                 /* new variable in object: colbits */
06938                 Object *ob = main->object.first;
06939                 int a;
06940                 while(ob) {
06941                         ob->colbits= 0;
06942                         if(ob->totcol) {
06943                                 for(a=0; a<ob->totcol; a++) {
06944                                         if(ob->mat[a]) ob->colbits |= (1<<a);
06945                                 }
06946                         }
06947                         ob= ob->id.next;
06948                 }
06949         }
06950         if(main->versionfile <= 104) {
06951                 /* timeoffs moved */
06952                 Object *ob = main->object.first;
06953                 while(ob) {
06954                         if(ob->transflag & 1) {
06955                                 ob->transflag -= 1;
06956                                 ob->ipoflag |= OB_OFFS_OB;
06957                         }
06958                         ob= ob->id.next;
06959                 }
06960         }
06961         if(main->versionfile <= 105) {
06962                 Object *ob = main->object.first;
06963                 while(ob) {
06964                         ob->dupon= 1; ob->dupoff= 0;
06965                         ob->dupsta= 1; ob->dupend= 100;
06966                         ob= ob->id.next;
06967                 }
06968         }
06969         if(main->versionfile <= 106) {
06970                 /* mcol changed */
06971                 Mesh *me = main->mesh.first;
06972                 while(me) {
06973                         if(me->mcol) vcol_to_fcol(me);
06974                         me= me->id.next;
06975                 }
06976 
06977         }
06978         if(main->versionfile <= 107) {
06979                 Object *ob;
06980                 Scene *sce = main->scene.first;
06981                 while(sce) {
06982                         sce->r.mode |= R_GAMMA;
06983                         sce= sce->id.next;
06984                 }
06985                 ob= main->object.first;
06986                 while(ob) {
06987                         ob->ipoflag |= OB_OFFS_PARENT;
06988                         if(ob->dt==0) ob->dt= OB_SOLID;
06989                         ob= ob->id.next;
06990                 }
06991 
06992         }
06993         if(main->versionfile <= 109) {
06994                 /* new variable: gridlines */
06995                 bScreen *sc = main->screen.first;
06996                 while(sc) {
06997                         ScrArea *sa= sc->areabase.first;
06998                         while(sa) {
06999                                 SpaceLink *sl= sa->spacedata.first;
07000                                 while (sl) {
07001                                         if (sl->spacetype==SPACE_VIEW3D) {
07002                                                 View3D *v3d= (View3D*) sl;
07003 
07004                                                 if (v3d->gridlines==0) v3d->gridlines= 20;
07005                                         }
07006                                         sl= sl->next;
07007                                 }
07008                                 sa= sa->next;
07009                         }
07010                         sc= sc->id.next;
07011                 }
07012         }
07013         if(main->versionfile <= 113) {
07014                 Material *ma = main->mat.first;
07015                 while(ma) {
07016                         if(ma->flaresize==0.0f) ma->flaresize= 1.0f;
07017                         ma->subsize= 1.0f;
07018                         ma->flareboost= 1.0f;
07019                         ma= ma->id.next;
07020                 }
07021         }
07022 
07023         if(main->versionfile <= 134) {
07024                 Tex *tex = main->tex.first;
07025                 while (tex) {
07026                         if ((tex->rfac == 0.0f) &&
07027                                 (tex->gfac == 0.0f) &&
07028                                 (tex->bfac == 0.0f)) {
07029                                 tex->rfac = 1.0f;
07030                                 tex->gfac = 1.0f;
07031                                 tex->bfac = 1.0f;
07032                                 tex->filtersize = 1.0f;
07033                         }
07034                         tex = tex->id.next;
07035                 }
07036         }
07037         if(main->versionfile <= 140) {
07038                 /* r-g-b-fac in texture */
07039                 Tex *tex = main->tex.first;
07040                 while (tex) {
07041                         if ((tex->rfac == 0.0f) &&
07042                                 (tex->gfac == 0.0f) &&
07043                                 (tex->bfac == 0.0f)) {
07044                                 tex->rfac = 1.0f;
07045                                 tex->gfac = 1.0f;
07046                                 tex->bfac = 1.0f;
07047                                 tex->filtersize = 1.0f;
07048                         }
07049                         tex = tex->id.next;
07050                 }
07051         }
07052         if(main->versionfile <= 153) {
07053                 Scene *sce = main->scene.first;
07054                 while(sce) {
07055                         if(sce->r.blurfac==0.0f) sce->r.blurfac= 1.0f;
07056                         sce= sce->id.next;
07057                 }
07058         }
07059         if(main->versionfile <= 163) {
07060                 Scene *sce = main->scene.first;
07061                 while(sce) {
07062                         if(sce->r.frs_sec==0) sce->r.frs_sec= 25;
07063                         sce= sce->id.next;
07064                 }
07065         }
07066         if(main->versionfile <= 164) {
07067                 Mesh *me= main->mesh.first;
07068                 while(me) {
07069                         me->smoothresh= 30;
07070                         me= me->id.next;
07071                 }
07072         }
07073         if(main->versionfile <= 165) {
07074                 Mesh *me= main->mesh.first;
07075                 TFace *tface;
07076                 int nr;
07077                 char *cp;
07078 
07079                 while(me) {
07080                         if(me->tface) {
07081                                 nr= me->totface;
07082                                 tface= me->tface;
07083                                 while(nr--) {
07084                                         cp= (char *)&tface->col[0];
07085                                         if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
07086                                         if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
07087                                         if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
07088                                         cp= (char *)&tface->col[1];
07089                                         if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
07090                                         if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
07091                                         if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
07092                                         cp= (char *)&tface->col[2];
07093                                         if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
07094                                         if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
07095                                         if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
07096                                         cp= (char *)&tface->col[3];
07097                                         if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
07098                                         if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
07099                                         if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
07100 
07101                                         tface++;
07102                                 }
07103                         }
07104                         me= me->id.next;
07105                 }
07106         }
07107 
07108         if(main->versionfile <= 169) {
07109                 Mesh *me= main->mesh.first;
07110                 while(me) {
07111                         if(me->subdiv==0) me->subdiv= 1;
07112                         me= me->id.next;
07113                 }
07114         }
07115 
07116         if(main->versionfile <= 169) {
07117                 bScreen *sc= main->screen.first;
07118                 while(sc) {
07119                         ScrArea *sa= sc->areabase.first;
07120                         while(sa) {
07121                                 SpaceLink *sl= sa->spacedata.first;
07122                                 while(sl) {
07123                                         if(sl->spacetype==SPACE_IPO) {
07124                                                 SpaceIpo *sipo= (SpaceIpo*) sl;
07125                                                 sipo->v2d.max[0]= 15000.0;
07126                                         }
07127                                         sl= sl->next;
07128                                 }
07129                                 sa= sa->next;
07130                         }
07131                         sc= sc->id.next;
07132                 }
07133         }
07134 
07135         if(main->versionfile <= 170) {
07136                 Object *ob = main->object.first;
07137                 PartEff *paf;
07138                 while (ob) {
07139                         paf = give_parteff(ob);
07140                         if (paf) {
07141                                 if (paf->staticstep == 0) {
07142                                         paf->staticstep= 5;
07143                                 }
07144                         }
07145                         ob = ob->id.next;
07146                 }
07147         }
07148 
07149         if(main->versionfile <= 171) {
07150                 bScreen *sc= main->screen.first;
07151                 while(sc) {
07152                         ScrArea *sa= sc->areabase.first;
07153                         while(sa) {
07154                                 SpaceLink *sl= sa->spacedata.first;
07155                                 while(sl) {
07156                                         if(sl->spacetype==SPACE_TEXT) {
07157                                                 SpaceText *st= (SpaceText*) sl;
07158                                                 st->lheight= 12;
07159                                         }
07160                                         sl= sl->next;
07161                                 }
07162                                 sa= sa->next;
07163                         }
07164                         sc= sc->id.next;
07165                 }
07166         }
07167 
07168         if(main->versionfile <= 173) {
07169                 int a, b;
07170                 Mesh *me= main->mesh.first;
07171                 while(me) {
07172                         if(me->tface) {
07173                                 TFace *tface= me->tface;
07174                                 for(a=0; a<me->totface; a++, tface++) {
07175                                         for(b=0; b<4; b++) {
07176                                                 tface->uv[b][0]/= 32767.0f;
07177                                                 tface->uv[b][1]/= 32767.0f;
07178                                         }
07179                                 }
07180                         }
07181                         me= me->id.next;
07182                 }
07183         }
07184 
07185         if(main->versionfile <= 191) {
07186                 Object *ob= main->object.first;
07187                 Material *ma = main->mat.first;
07188 
07189                 /* let faces have default add factor of 0.0 */
07190                 while(ma) {
07191                   if (!(ma->mode & MA_HALO)) ma->add = 0.0;
07192                   ma = ma->id.next;
07193                 }
07194 
07195                 while(ob) {
07196                         ob->mass= 1.0f;
07197                         ob->damping= 0.1f;
07198                         /*ob->quat[1]= 1.0f;*/ /* quats arnt used yet */
07199                         ob= ob->id.next;
07200                 }
07201         }
07202 
07203         if(main->versionfile <= 193) {
07204                 Object *ob= main->object.first;
07205                 while(ob) {
07206                         ob->inertia= 1.0f;
07207                         ob->rdamping= 0.1f;
07208                         ob= ob->id.next;
07209                 }
07210         }
07211 
07212         if(main->versionfile <= 196) {
07213                 Mesh *me= main->mesh.first;
07214                 int a, b;
07215                 while(me) {
07216                         if(me->tface) {
07217                                 TFace *tface= me->tface;
07218                                 for(a=0; a<me->totface; a++, tface++) {
07219                                         for(b=0; b<4; b++) {
07220                                                 tface->mode |= TF_DYNAMIC;
07221                                                 tface->mode &= ~TF_INVISIBLE;
07222                                         }
07223                                 }
07224                         }
07225                         me= me->id.next;
07226                 }
07227         }
07228 
07229         if(main->versionfile <= 200) {
07230                 Object *ob= main->object.first;
07231                 while(ob) {
07232                         ob->scaflag = ob->gameflag & (64+128+256+512+1024+2048);
07233                                 /* 64 is do_fh */
07234                         ob->gameflag &= ~(128+256+512+1024+2048);
07235                         ob = ob->id.next;
07236                 }
07237         }
07238 
07239         if(main->versionfile <= 201) {
07240                 /* add-object + end-object are joined to edit-object actuator */
07241                 Object *ob = main->object.first;
07242                 bProperty *prop;
07243                 bActuator *act;
07244                 bIpoActuator *ia;
07245                 bEditObjectActuator *eoa;
07246                 bAddObjectActuator *aoa;
07247                 while (ob) {
07248                         act = ob->actuators.first;
07249                         while (act) {
07250                                 if(act->type==ACT_IPO) {
07251                                         ia= act->data;
07252                                         prop= get_ob_property(ob, ia->name);
07253                                         if(prop) {
07254                                                 ia->type= ACT_IPO_FROM_PROP;
07255                                         }
07256                                 }
07257                                 else if(act->type==ACT_ADD_OBJECT) {
07258                                         aoa= act->data;
07259                                         eoa= MEM_callocN(sizeof(bEditObjectActuator), "edit ob act");
07260                                         eoa->type= ACT_EDOB_ADD_OBJECT;
07261                                         eoa->ob= aoa->ob;
07262                                         eoa->time= aoa->time;
07263                                         MEM_freeN(aoa);
07264                                         act->data= eoa;
07265                                         act->type= act->otype= ACT_EDIT_OBJECT;
07266                                 }
07267                                 else if(act->type==ACT_END_OBJECT) {
07268                                         eoa= MEM_callocN(sizeof(bEditObjectActuator), "edit ob act");
07269                                         eoa->type= ACT_EDOB_END_OBJECT;
07270                                         act->data= eoa;
07271                                         act->type= act->otype= ACT_EDIT_OBJECT;
07272                                 }
07273                                 act= act->next;
07274                         }
07275                         ob = ob->id.next;
07276                 }
07277         }
07278 
07279         if(main->versionfile <= 202) {
07280                 /* add-object and end-object are joined to edit-object
07281                  * actuator */
07282                 Object *ob= main->object.first;
07283                 bActuator *act;
07284                 bObjectActuator *oa;
07285                 while(ob) {
07286                         act= ob->actuators.first;
07287                         while(act) {
07288                                 if(act->type==ACT_OBJECT) {
07289                                         oa= act->data;
07290                                         oa->flag &= ~(ACT_TORQUE_LOCAL|ACT_DROT_LOCAL);         /* this actuator didn't do local/glob rot before */
07291                                 }
07292                                 act= act->next;
07293                         }
07294                         ob= ob->id.next;
07295                 }
07296         }
07297 
07298         if(main->versionfile <= 204) {
07299                 /* patches for new physics */
07300                 Object *ob= main->object.first;
07301                 bActuator *act;
07302                 bObjectActuator *oa;
07303                 bSound *sound;
07304                 while(ob) {
07305 
07306                         /* please check this for demo20 files like
07307                          * original Egypt levels etc.  converted
07308                          * rotation factor of 50 is not workable */
07309                         act= ob->actuators.first;
07310                         while(act) {
07311                                 if(act->type==ACT_OBJECT) {
07312                                         oa= act->data;
07313 
07314                                         oa->forceloc[0]*= 25.0f;
07315                                         oa->forceloc[1]*= 25.0f;
07316                                         oa->forceloc[2]*= 25.0f;
07317 
07318                                         oa->forcerot[0]*= 10.0f;
07319                                         oa->forcerot[1]*= 10.0f;
07320                                         oa->forcerot[2]*= 10.0f;
07321                                 }
07322                                 act= act->next;
07323                         }
07324                         ob= ob->id.next;
07325                 }
07326 
07327                 sound = main->sound.first;
07328                 while (sound) {
07329                         if (sound->volume < 0.01f) {
07330                                 sound->volume = 1.0f;
07331                         }
07332                         sound = sound->id.next;
07333                 }
07334         }
07335 
07336         if(main->versionfile <= 205) {
07337                 /* patches for new physics */
07338                 Object *ob= main->object.first;
07339                 bActuator *act;
07340                 bSensor *sens;
07341                 bEditObjectActuator *oa;
07342                 bRaySensor *rs;
07343                 bCollisionSensor *cs;
07344                 while(ob) {
07345                         /* Set anisotropic friction off for old objects,
07346                          * values to 1.0.  */
07347                         ob->gameflag &= ~OB_ANISOTROPIC_FRICTION;
07348                         ob->anisotropicFriction[0] = 1.0;
07349                         ob->anisotropicFriction[1] = 1.0;
07350                         ob->anisotropicFriction[2] = 1.0;
07351 
07352                         act= ob->actuators.first;
07353                         while(act) {
07354                                 if(act->type==ACT_EDIT_OBJECT) {
07355                                         /* Zero initial velocity for newly
07356                                          * added objects */
07357                                         oa= act->data;
07358                                         oa->linVelocity[0] = 0.0;
07359                                         oa->linVelocity[1] = 0.0;
07360                                         oa->linVelocity[2] = 0.0;
07361                                         oa->localflag = 0;
07362                                 }
07363                                 act= act->next;
07364                         }
07365 
07366                         sens= ob->sensors.first;
07367                         while (sens) {
07368                                 /* Extra fields for radar sensors. */
07369                                 if(sens->type == SENS_RADAR) {
07370                                         bRadarSensor *s = sens->data;
07371                                         s->range = 10000.0;
07372                                 }
07373 
07374                                 /* Pulsing: defaults for new sensors. */
07375                                 if(sens->type != SENS_ALWAYS) {
07376                                         sens->pulse = 0;
07377                                         sens->freq = 0;
07378                                 } else {
07379                                         sens->pulse = 1;
07380                                 }
07381 
07382                                 /* Invert: off. */
07383                                 sens->invert = 0;
07384 
07385                                 /* Collision and ray: default = trigger
07386                                  * on property. The material field can
07387                                  * remain empty. */
07388                                 if(sens->type == SENS_COLLISION) {
07389                                         cs = (bCollisionSensor*) sens->data;
07390                                         cs->mode = 0;
07391                                 }
07392                                 if(sens->type == SENS_RAY) {
07393                                         rs = (bRaySensor*) sens->data;
07394                                         rs->mode = 0;
07395                                 }
07396                                 sens = sens->next;
07397                         }
07398                         ob= ob->id.next;
07399                 }
07400                 /* have to check the exact multiplier */
07401         }
07402 
07403         if(main->versionfile <= 211) {
07404                 /* Render setting: per scene, the applicable gamma value
07405                  * can be set. Default is 1.0, which means no
07406                  * correction.  */
07407                 bActuator *act;
07408                 bObjectActuator *oa;
07409                 Object *ob;
07410 
07411                 /* added alpha in obcolor */
07412                 ob= main->object.first;
07413                 while(ob) {
07414                         ob->col[3]= 1.0;
07415                         ob= ob->id.next;
07416                 }
07417 
07418                 /* added alpha in obcolor */
07419                 ob= main->object.first;
07420                 while(ob) {
07421                         act= ob->actuators.first;
07422                         while(act) {
07423                                 if (act->type==ACT_OBJECT) {
07424                                         /* multiply velocity with 50 in old files */
07425                                         oa= act->data;
07426                                         if (fabsf(oa->linearvelocity[0]) >= 0.01f)
07427                                                 oa->linearvelocity[0] *= 50.0f;
07428                                         if (fabsf(oa->linearvelocity[1]) >= 0.01f)
07429                                                 oa->linearvelocity[1] *= 50.0f;
07430                                         if (fabsf(oa->linearvelocity[2]) >= 0.01f)
07431                                                 oa->linearvelocity[2] *= 50.0f;
07432                                         if (fabsf(oa->angularvelocity[0])>=0.01f)
07433                                                 oa->angularvelocity[0] *= 50.0f;
07434                                         if (fabsf(oa->angularvelocity[1])>=0.01f)
07435                                                 oa->angularvelocity[1] *= 50.0f;
07436                                         if (fabsf(oa->angularvelocity[2])>=0.01f)
07437                                                 oa->angularvelocity[2] *= 50.0f;
07438                                 }
07439                                 act= act->next;
07440                         }
07441                         ob= ob->id.next;
07442                 }
07443         }
07444 
07445         if(main->versionfile <= 212) {
07446 
07447                 bSound* sound;
07448                 bProperty *prop;
07449                 Object *ob;
07450                 Mesh *me;
07451 
07452                 sound = main->sound.first;
07453                 while (sound)
07454                 {
07455                         sound->max_gain = 1.0;
07456                         sound->min_gain = 0.0;
07457                         sound->distance = 1.0;
07458 
07459                         if (sound->attenuation > 0.0f)
07460                                 sound->flags |= SOUND_FLAGS_3D;
07461                         else
07462                                 sound->flags &= ~SOUND_FLAGS_3D;
07463 
07464                         sound = sound->id.next;
07465                 }
07466 
07467                 ob = main->object.first;
07468 
07469                 while (ob) {
07470                         prop= ob->prop.first;
07471                         while(prop) {
07472                                 if (prop->type == GPROP_TIME) {
07473                                         // convert old GPROP_TIME values from int to float
07474                                         *((float *)&prop->data) = (float) prop->data;
07475                                 }
07476 
07477                                 prop= prop->next;
07478                         }
07479                         ob = ob->id.next;
07480                 }
07481 
07482                         /* me->subdiv changed to reflect the actual reparametization
07483                          * better, and smeshes were removed - if it was a smesh make
07484                          * it a subsurf, and reset the subdiv level because subsurf
07485                          * takes a lot more work to calculate.
07486                          */
07487                 for (me= main->mesh.first; me; me= me->id.next) {
07488                         if (me->flag&ME_SMESH) {
07489                                 me->flag&= ~ME_SMESH;
07490                                 me->flag|= ME_SUBSURF;
07491 
07492                                 me->subdiv= 1;
07493                         } else {
07494                                 if (me->subdiv<2)
07495                                         me->subdiv= 1;
07496                                 else
07497                                         me->subdiv--;
07498                         }
07499                 }
07500         }
07501 
07502         if(main->versionfile <= 220) {
07503                 Object *ob;
07504                 Mesh *me;
07505 
07506                 ob = main->object.first;
07507 
07508                 /* adapt form factor in order to get the 'old' physics
07509                  * behaviour back...*/
07510 
07511                 while (ob) {
07512                         /* in future, distinguish between different
07513                          * object bounding shapes */
07514                         ob->formfactor = 0.4f;
07515                         /* patch form factor , note that inertia equiv radius
07516                          * of a rotation symmetrical obj */
07517                         if (ob->inertia != 1.0f) {
07518                                 ob->formfactor /= ob->inertia * ob->inertia;
07519                         }
07520                         ob = ob->id.next;
07521                 }
07522 
07523                         /* Began using alpha component of vertex colors, but
07524                          * old file vertex colors are undefined, reset them
07525                          * to be fully opaque. -zr
07526                          */
07527                 for (me= main->mesh.first; me; me= me->id.next) {
07528                         if (me->mcol) {
07529                                 int i;
07530 
07531                                 for (i=0; i<me->totface*4; i++) {
07532                                         MCol *mcol= &me->mcol[i];
07533                                         mcol->a= 255;
07534                                 }
07535                         }
07536                         if (me->tface) {
07537                                 int i, j;
07538 
07539                                 for (i=0; i<me->totface; i++) {
07540                                         TFace *tf= &((TFace*) me->tface)[i];
07541 
07542                                         for (j=0; j<4; j++) {
07543                                                 char *col= (char*) &tf->col[j];
07544 
07545                                                 col[0]= 255;
07546                                         }
07547                                 }
07548                         }
07549                 }
07550         }
07551         if(main->versionfile <= 221) {
07552                 Scene *sce= main->scene.first;
07553 
07554                 // new variables for std-alone player and runtime
07555                 while(sce) {
07556 
07557                         sce->r.xplay= 640;
07558                         sce->r.yplay= 480;
07559                         sce->r.freqplay= 60;
07560 
07561                         sce= sce->id.next;
07562                 }
07563 
07564         }
07565         if(main->versionfile <= 222) {
07566                 Scene *sce= main->scene.first;
07567 
07568                 // new variables for std-alone player and runtime
07569                 while(sce) {
07570 
07571                         sce->r.depth= 32;
07572 
07573                         sce= sce->id.next;
07574                 }
07575         }
07576 
07577 
07578         if(main->versionfile <= 223) {
07579                 VFont *vf;
07580                 Image *ima;
07581                 Object *ob;
07582 
07583                 for (vf= main->vfont.first; vf; vf= vf->id.next) {
07584                         if (strcmp(vf->name+strlen(vf->name)-6, ".Bfont")==0) {
07585                                 strcpy(vf->name, FO_BUILTIN_NAME);
07586                         }
07587                 }
07588 
07589                 /* Old textures animate at 25 FPS */
07590                 for (ima = main->image.first; ima; ima=ima->id.next){
07591                         ima->animspeed = 25;
07592                 }
07593 
07594                         /* Zr remapped some keyboard codes to be linear (stupid zr) */
07595                 for (ob= main->object.first; ob; ob= ob->id.next) {
07596                         bSensor *sens;
07597 
07598                         for (sens= ob->sensors.first; sens; sens= sens->next) {
07599                                 if (sens->type==SENS_KEYBOARD) {
07600                                         bKeyboardSensor *ks= sens->data;
07601 
07602                                         ks->key= map_223_keybd_code_to_224_keybd_code(ks->key);
07603                                         ks->qual= map_223_keybd_code_to_224_keybd_code(ks->qual);
07604                                         ks->qual2= map_223_keybd_code_to_224_keybd_code(ks->qual2);
07605                                 }
07606                         }
07607                 }
07608         }
07609         if(main->versionfile <= 224) {
07610                 bSound* sound;
07611                 Scene *sce;
07612                 Mesh *me;
07613                 bScreen *sc;
07614 
07615                 for (sound=main->sound.first; sound; sound=sound->id.next) {
07616                         if (sound->packedfile) {
07617                                 if (sound->newpackedfile == NULL) {
07618                                         sound->newpackedfile = sound->packedfile;
07619                                 }
07620                                 sound->packedfile = NULL;
07621                         }
07622                 }
07623                 /* Make sure that old subsurf meshes don't have zero subdivision level for rendering */
07624                 for (me=main->mesh.first; me; me=me->id.next){
07625                         if ((me->flag & ME_SUBSURF) && (me->subdivr==0))
07626                                 me->subdivr=me->subdiv;
07627                 }
07628 
07629                 for (sce= main->scene.first; sce; sce= sce->id.next) {
07630                         sce->r.stereomode = 1;  // no stereo
07631                 }
07632 
07633                         /* some oldfile patch, moved from set_func_space */
07634                 for (sc= main->screen.first; sc; sc= sc->id.next) {
07635                         ScrArea *sa;
07636 
07637                         for (sa= sc->areabase.first; sa; sa= sa->next) {
07638                                 SpaceLink *sl;
07639 
07640                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
07641                                         if (sl->spacetype==SPACE_IPO) {
07642                                                 SpaceSeq *sseq= (SpaceSeq*) sl;
07643                                                 sseq->v2d.keeptot= 0;
07644                                         }
07645                                 }
07646                         }
07647                 }
07648 
07649         }
07650 
07651 
07652         if(main->versionfile <= 225) {
07653                 World *wo;
07654                 /* Use Sumo for old games */
07655                 for (wo = main->world.first; wo; wo= wo->id.next) {
07656                         wo->physicsEngine = 2;
07657                 }
07658         }
07659 
07660         if(main->versionfile <= 227) {
07661                 Scene *sce;
07662                 Material *ma;
07663                 bScreen *sc;
07664                 Object *ob;
07665 
07666                 /*  As of now, this insures that the transition from the old Track system
07667                         to the new full constraint Track is painless for everyone. - theeth
07668                 */
07669                 ob = main->object.first;
07670 
07671                 while (ob) {
07672                         ListBase *list;
07673                         list = &ob->constraints;
07674 
07675                         /* check for already existing TrackTo constraint
07676                            set their track and up flag correctly */
07677 
07678                         if (list){
07679                                 bConstraint *curcon;
07680                                 for (curcon = list->first; curcon; curcon=curcon->next){
07681                                         if (curcon->type == CONSTRAINT_TYPE_TRACKTO){
07682                                                 bTrackToConstraint *data = curcon->data;
07683                                                 data->reserved1 = ob->trackflag;
07684                                                 data->reserved2 = ob->upflag;
07685                                         }
07686                                 }
07687                         }
07688 
07689                         if (ob->type == OB_ARMATURE) {
07690                                 if (ob->pose){
07691                                         bConstraint *curcon;
07692                                         bPoseChannel *pchan;
07693                                         for (pchan = ob->pose->chanbase.first;
07694                                                  pchan; pchan=pchan->next){
07695                                                 for (curcon = pchan->constraints.first;
07696                                                          curcon; curcon=curcon->next){
07697                                                         if (curcon->type == CONSTRAINT_TYPE_TRACKTO){
07698                                                                 bTrackToConstraint *data = curcon->data;
07699                                                                 data->reserved1 = ob->trackflag;
07700                                                                 data->reserved2 = ob->upflag;
07701                                                         }
07702                                                 }
07703                                         }
07704                                 }
07705                         }
07706 
07707                         /* Change Ob->Track in real TrackTo constraint */
07708                         do_version_old_trackto_to_constraints(ob);
07709                         
07710                         ob = ob->id.next;
07711                 }
07712 
07713 
07714                 for (sce= main->scene.first; sce; sce= sce->id.next) {
07715                         sce->audio.mixrate = 44100;
07716                         sce->audio.flag |= AUDIO_SCRUB;
07717                         sce->r.mode |= R_ENVMAP;
07718                 }
07719                 // init new shader vars
07720                 for (ma= main->mat.first; ma; ma= ma->id.next) {
07721                         ma->refrac= 4.0f;
07722                         ma->roughness= 0.5f;
07723                         ma->param[0]= 0.5f;
07724                         ma->param[1]= 0.1f;
07725                         ma->param[2]= 0.1f;
07726                         ma->param[3]= 0.05f;
07727                 }
07728                 // patch for old wrong max view2d settings, allows zooming out more
07729                 for (sc= main->screen.first; sc; sc= sc->id.next) {
07730                         ScrArea *sa;
07731 
07732                         for (sa= sc->areabase.first; sa; sa= sa->next) {
07733                                 SpaceLink *sl;
07734 
07735                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
07736                                         if (sl->spacetype==SPACE_ACTION) {
07737                                                 SpaceAction *sac= (SpaceAction *) sl;
07738                                                 sac->v2d.max[0]= 32000;
07739                                         }
07740                                         else if (sl->spacetype==SPACE_NLA) {
07741                                                 SpaceNla *sla= (SpaceNla *) sl;
07742                                                 sla->v2d.max[0]= 32000;
07743                                         }
07744                                 }
07745                         }
07746                 }
07747         }
07748         if(main->versionfile <= 228) {
07749                 Scene *sce;
07750                 bScreen *sc;
07751                 Object *ob;
07752 
07753 
07754                 /*  As of now, this insures that the transition from the old Track system
07755                         to the new full constraint Track is painless for everyone.*/
07756                 ob = main->object.first;
07757 
07758                 while (ob) {
07759                         ListBase *list;
07760                         list = &ob->constraints;
07761 
07762                         /* check for already existing TrackTo constraint
07763                            set their track and up flag correctly */
07764 
07765                         if (list){
07766                                 bConstraint *curcon;
07767                                 for (curcon = list->first; curcon; curcon=curcon->next){
07768                                         if (curcon->type == CONSTRAINT_TYPE_TRACKTO){
07769                                                 bTrackToConstraint *data = curcon->data;
07770                                                 data->reserved1 = ob->trackflag;
07771                                                 data->reserved2 = ob->upflag;
07772                                         }
07773                                 }
07774                         }
07775 
07776                         if (ob->type == OB_ARMATURE) {
07777                                 if (ob->pose){
07778                                         bConstraint *curcon;
07779                                         bPoseChannel *pchan;
07780                                         for (pchan = ob->pose->chanbase.first;
07781                                                  pchan; pchan=pchan->next){
07782                                                 for (curcon = pchan->constraints.first;
07783                                                          curcon; curcon=curcon->next){
07784                                                         if (curcon->type == CONSTRAINT_TYPE_TRACKTO){
07785                                                                 bTrackToConstraint *data = curcon->data;
07786                                                                 data->reserved1 = ob->trackflag;
07787                                                                 data->reserved2 = ob->upflag;
07788                                                         }
07789                                                 }
07790                                         }
07791                                 }
07792                         }
07793 
07794                         ob = ob->id.next;
07795                 }
07796 
07797                 for (sce= main->scene.first; sce; sce= sce->id.next) {
07798                         sce->r.mode |= R_ENVMAP;
07799                 }
07800 
07801                 // convert old mainb values for new button panels
07802                 for (sc= main->screen.first; sc; sc= sc->id.next) {
07803                         ScrArea *sa;
07804 
07805                         for (sa= sc->areabase.first; sa; sa= sa->next) {
07806                                 SpaceLink *sl;
07807 
07808                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
07809                                         if (sl->spacetype==SPACE_BUTS) {
07810                                                 SpaceButs *sbuts= (SpaceButs *) sl;
07811 
07812                                                 sbuts->v2d.maxzoom= 1.2f;
07813                                                 sbuts->align= 1;        /* horizontal default */
07814                                         
07815                                                 if(sbuts->mainb==BUTS_LAMP) {
07816                                                         sbuts->mainb= CONTEXT_SHADING;
07817                                                         //sbuts->tab[CONTEXT_SHADING]= TAB_SHADING_LAMP;
07818                                                 }
07819                                                 else if(sbuts->mainb==BUTS_MAT) {
07820                                                         sbuts->mainb= CONTEXT_SHADING;
07821                                                         //sbuts->tab[CONTEXT_SHADING]= TAB_SHADING_MAT;
07822                                                 }
07823                                                 else if(sbuts->mainb==BUTS_TEX) {
07824                                                         sbuts->mainb= CONTEXT_SHADING;
07825                                                         //sbuts->tab[CONTEXT_SHADING]= TAB_SHADING_TEX;
07826                                                 }
07827                                                 else if(sbuts->mainb==BUTS_ANIM) {
07828                                                         sbuts->mainb= CONTEXT_OBJECT;
07829                                                 }
07830                                                 else if(sbuts->mainb==BUTS_WORLD) {
07831                                                         sbuts->mainb= CONTEXT_SCENE;
07832                                                         //sbuts->tab[CONTEXT_SCENE]= TAB_SCENE_WORLD;
07833                                                 }
07834                                                 else if(sbuts->mainb==BUTS_RENDER) {
07835                                                         sbuts->mainb= CONTEXT_SCENE;
07836                                                         //sbuts->tab[CONTEXT_SCENE]= TAB_SCENE_RENDER;
07837                                                 }
07838                                                 else if(sbuts->mainb==BUTS_GAME) {
07839                                                         sbuts->mainb= CONTEXT_LOGIC;
07840                                                 }
07841                                                 else if(sbuts->mainb==BUTS_FPAINT) {
07842                                                         sbuts->mainb= CONTEXT_EDITING;
07843                                                 }
07844                                                 else if(sbuts->mainb==BUTS_RADIO) {
07845                                                         sbuts->mainb= CONTEXT_SHADING;
07846                                                         //sbuts->tab[CONTEXT_SHADING]= TAB_SHADING_RAD;
07847                                                 }
07848                                                 else if(sbuts->mainb==BUTS_CONSTRAINT) {
07849                                                         sbuts->mainb= CONTEXT_OBJECT;
07850                                                 }
07851                                                 else if(sbuts->mainb==BUTS_SCRIPT) {
07852                                                         sbuts->mainb= CONTEXT_OBJECT;
07853                                                 }
07854                                                 else if(sbuts->mainb==BUTS_EDIT) {
07855                                                         sbuts->mainb= CONTEXT_EDITING;
07856                                                 }
07857                                                 else sbuts->mainb= CONTEXT_SCENE;
07858                                         }
07859                                 }
07860                         }
07861                 }
07862         }
07863         /* ton: made this 230 instead of 229,
07864            to be sure (tuho files) and this is a reliable check anyway
07865            nevertheless, we might need to think over a fitness (initialize)
07866            check apart from the do_versions() */
07867 
07868         if(main->versionfile <= 230) {
07869                 bScreen *sc;
07870 
07871                 // new variable blockscale, for panels in any area
07872                 for (sc= main->screen.first; sc; sc= sc->id.next) {
07873                         ScrArea *sa;
07874 
07875                         for (sa= sc->areabase.first; sa; sa= sa->next) {
07876                                 SpaceLink *sl;
07877 
07878                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
07879                                         if(sl->blockscale==0.0f) sl->blockscale= 0.7f;
07880                                         /* added: 5x better zoom in for action */
07881                                         if(sl->spacetype==SPACE_ACTION) {
07882                                                 SpaceAction *sac= (SpaceAction *)sl;
07883                                                 sac->v2d.maxzoom= 50;
07884                                         }
07885                                 }
07886                         }
07887                 }
07888         }
07889         if(main->versionfile <= 231) {
07890                 /* new bit flags for showing/hiding grid floor and axes */
07891                 bScreen *sc = main->screen.first;
07892                 while(sc) {
07893                         ScrArea *sa= sc->areabase.first;
07894                         while(sa) {
07895                                 SpaceLink *sl= sa->spacedata.first;
07896                                 while (sl) {
07897                                         if (sl->spacetype==SPACE_VIEW3D) {
07898                                                 View3D *v3d= (View3D*) sl;
07899 
07900                                                 if (v3d->gridflag==0) {
07901                                                         v3d->gridflag |= V3D_SHOW_X;
07902                                                         v3d->gridflag |= V3D_SHOW_Y;
07903                                                         v3d->gridflag |= V3D_SHOW_FLOOR;
07904                                                         v3d->gridflag &= ~V3D_SHOW_Z;
07905                                                 }
07906                                         }
07907                                         sl= sl->next;
07908                                 }
07909                                 sa= sa->next;
07910                         }
07911                         sc= sc->id.next;
07912                 }
07913         }
07914         if(main->versionfile <= 231) {
07915                 Material *ma= main->mat.first;
07916                 bScreen *sc = main->screen.first;
07917                 Scene *sce;
07918                 Lamp *la;
07919                 World *wrld;
07920 
07921                 /* introduction of raytrace */
07922                 while(ma) {
07923                         if(ma->fresnel_tra_i==0.0f) ma->fresnel_tra_i= 1.25f;
07924                         if(ma->fresnel_mir_i==0.0f) ma->fresnel_mir_i= 1.25f;
07925 
07926                         ma->ang= 1.0;
07927                         ma->ray_depth= 2;
07928                         ma->ray_depth_tra= 2;
07929                         ma->fresnel_tra= 0.0;
07930                         ma->fresnel_mir= 0.0;
07931 
07932                         ma= ma->id.next;
07933                 }
07934                 sce= main->scene.first;
07935                 while(sce) {
07936                         if(sce->r.gauss==0.0f) sce->r.gauss= 1.0f;
07937                         sce= sce->id.next;
07938                 }
07939                 la= main->lamp.first;
07940                 while(la) {
07941                         if(la->k==0.0f) la->k= 1.0;
07942                         if(la->ray_samp==0) la->ray_samp= 1;
07943                         if(la->ray_sampy==0) la->ray_sampy= 1;
07944                         if(la->ray_sampz==0) la->ray_sampz= 1;
07945                         if(la->area_size==0.0f) la->area_size= 1.0f;
07946                         if(la->area_sizey==0.0f) la->area_sizey= 1.0f;
07947                         if(la->area_sizez==0.0f) la->area_sizez= 1.0f;
07948                         la= la->id.next;
07949                 }
07950                 wrld= main->world.first;
07951                 while(wrld) {
07952                         if(wrld->range==0.0f) {
07953                                 wrld->range= 1.0f/wrld->exposure;
07954                         }
07955                         wrld= wrld->id.next;
07956                 }
07957 
07958                 /* new bit flags for showing/hiding grid floor and axes */
07959 
07960                 while(sc) {
07961                         ScrArea *sa= sc->areabase.first;
07962                         while(sa) {
07963                                 SpaceLink *sl= sa->spacedata.first;
07964                                 while (sl) {
07965                                         if (sl->spacetype==SPACE_VIEW3D) {
07966                                                 View3D *v3d= (View3D*) sl;
07967 
07968                                                 if (v3d->gridflag==0) {
07969                                                         v3d->gridflag |= V3D_SHOW_X;
07970                                                         v3d->gridflag |= V3D_SHOW_Y;
07971                                                         v3d->gridflag |= V3D_SHOW_FLOOR;
07972                                                         v3d->gridflag &= ~V3D_SHOW_Z;
07973                                                 }
07974                                         }
07975                                         sl= sl->next;
07976                                 }
07977                                 sa= sa->next;
07978                         }
07979                         sc= sc->id.next;
07980                 }
07981         }
07982         if(main->versionfile <= 232) {
07983                 Tex *tex= main->tex.first;
07984                 World *wrld= main->world.first;
07985                 bScreen *sc;
07986                 Scene *sce;
07987 
07988                 while(tex) {
07989                         if((tex->flag & (TEX_CHECKER_ODD+TEX_CHECKER_EVEN))==0) {
07990                                 tex->flag |= TEX_CHECKER_ODD;
07991                         }
07992                         /* copied from kernel texture.c */
07993                         if(tex->ns_outscale==0.0f) {
07994                                 /* musgrave */
07995                                 tex->mg_H = 1.0f;
07996                                 tex->mg_lacunarity = 2.0f;
07997                                 tex->mg_octaves = 2.0f;
07998                                 tex->mg_offset = 1.0f;
07999                                 tex->mg_gain = 1.0f;
08000                                 tex->ns_outscale = 1.0f;
08001                                 /* distnoise */
08002                                 tex->dist_amount = 1.0f;
08003                                 /* voronoi */
08004                                 tex->vn_w1 = 1.0f;
08005                                 tex->vn_mexp = 2.5f;
08006                         }
08007                         tex= tex->id.next;
08008                 }
08009 
08010                 while(wrld) {
08011                         if(wrld->aodist==0.0f) {
08012                                 wrld->aodist= 10.0f;
08013                                 wrld->aobias= 0.05f;
08014                         }
08015                         if(wrld->aosamp==0) wrld->aosamp= 5;
08016                         if(wrld->aoenergy==0.0f) wrld->aoenergy= 1.0f;
08017                         wrld= wrld->id.next;
08018                 }
08019 
08020 
08021                 // new variable blockscale, for panels in any area, do again because new
08022                 // areas didnt initialize it to 0.7 yet
08023                 for (sc= main->screen.first; sc; sc= sc->id.next) {
08024                         ScrArea *sa;
08025                         for (sa= sc->areabase.first; sa; sa= sa->next) {
08026                                 SpaceLink *sl;
08027                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08028                                         if(sl->blockscale==0.0f) sl->blockscale= 0.7f;
08029 
08030                                         /* added: 5x better zoom in for nla */
08031                                         if(sl->spacetype==SPACE_NLA) {
08032                                                 SpaceNla *snla= (SpaceNla *)sl;
08033                                                 snla->v2d.maxzoom= 50;
08034                                         }
08035                                 }
08036                         }
08037                 }
08038                 sce= main->scene.first;
08039                 while(sce) {
08040                         if(sce->r.ocres==0) sce->r.ocres= 64;
08041                         sce= sce->id.next;
08042                 }
08043 
08044         }
08045         if(main->versionfile <= 233) {
08046                 bScreen *sc;
08047                 Material *ma= main->mat.first;
08048                 Object *ob= main->object.first;
08049                 
08050                 while(ma) {
08051                         if(ma->rampfac_col==0.0f) ma->rampfac_col= 1.0;
08052                         if(ma->rampfac_spec==0.0f) ma->rampfac_spec= 1.0;
08053                         if(ma->pr_lamp==0) ma->pr_lamp= 3;
08054                         ma= ma->id.next;
08055                 }
08056                 
08057                 /* this should have been done loooong before! */
08058                 while(ob) {
08059                         if(ob->ipowin==0) ob->ipowin= ID_OB;
08060                         ob= ob->id.next;
08061                 }
08062                 
08063                 for (sc= main->screen.first; sc; sc= sc->id.next) {
08064                         ScrArea *sa;
08065                         for (sa= sc->areabase.first; sa; sa= sa->next) {
08066                                 SpaceLink *sl;
08067                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08068                                         if(sl->spacetype==SPACE_VIEW3D) {
08069                                                 View3D *v3d= (View3D *)sl;
08070                                                 v3d->flag |= V3D_SELECT_OUTLINE;
08071                                         }
08072                                 }
08073                         }
08074                 }
08075         }
08076 
08077 
08078         
08079 
08080         if(main->versionfile <= 234) {
08081                 World *wo;
08082                 bScreen *sc;
08083                 
08084                 // force sumo engine to be active
08085                 for (wo = main->world.first; wo; wo= wo->id.next) {
08086                         if(wo->physicsEngine==0) wo->physicsEngine = 2;
08087                 }
08088                 
08089                 for (sc= main->screen.first; sc; sc= sc->id.next) {
08090                         ScrArea *sa;
08091                         for (sa= sc->areabase.first; sa; sa= sa->next) {
08092                                 SpaceLink *sl;
08093                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08094                                         if(sl->spacetype==SPACE_VIEW3D) {
08095                                                 View3D *v3d= (View3D *)sl;
08096                                                 v3d->flag |= V3D_ZBUF_SELECT;
08097                                         }
08098                                         else if(sl->spacetype==SPACE_TEXT) {
08099                                                 SpaceText *st= (SpaceText *)sl;
08100                                                 if(st->tabnumber==0) st->tabnumber= 2;
08101                                         }
08102                                 }
08103                         }
08104                 }
08105         }
08106         if(main->versionfile <= 235) {
08107                 Tex *tex= main->tex.first;
08108                 Scene *sce= main->scene.first;
08109                 Sequence *seq;
08110                 Editing *ed;
08111                 
08112                 while(tex) {
08113                         if(tex->nabla==0.0f) tex->nabla= 0.025f;
08114                         tex= tex->id.next;
08115                 }
08116                 while(sce) {
08117                         ed= sce->ed;
08118                         if(ed) {
08119                                 SEQ_BEGIN(sce->ed, seq) {
08120                                         if(seq->type==SEQ_IMAGE || seq->type==SEQ_MOVIE)
08121                                                 seq->flag |= SEQ_MAKE_PREMUL;
08122                                 }
08123                                 SEQ_END
08124                         }
08125                         
08126                         sce= sce->id.next;
08127                 }
08128         }
08129         if(main->versionfile <= 236) {
08130                 Object *ob;
08131                 Camera *cam= main->camera.first;
08132                 Material *ma;
08133                 bScreen *sc;
08134 
08135                 while(cam) {
08136                         if(cam->ortho_scale==0.0f) {
08137                                 cam->ortho_scale= 256.0f/cam->lens;
08138                                 if(cam->type==CAM_ORTHO) printf("NOTE: ortho render has changed, tweak new Camera 'scale' value.\n");
08139                         }
08140                         cam= cam->id.next;
08141                 }
08142                 /* set manipulator type */
08143                 /* force oops draw if depgraph was set*/
08144                 /* set time line var */
08145                 for (sc= main->screen.first; sc; sc= sc->id.next) {
08146                         ScrArea *sa;
08147                         for (sa= sc->areabase.first; sa; sa= sa->next) {
08148                                 SpaceLink *sl;
08149                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08150                                         if(sl->spacetype==SPACE_VIEW3D) {
08151                                                 View3D *v3d= (View3D *)sl;
08152                                                 if(v3d->twtype==0) v3d->twtype= V3D_MANIP_TRANSLATE;
08153                                         }
08154                                         else if(sl->spacetype==SPACE_TIME) {
08155                                                 SpaceTime *stime= (SpaceTime *)sl;
08156                                                 if(stime->redraws==0)
08157                                                         stime->redraws= TIME_ALL_3D_WIN|TIME_ALL_ANIM_WIN;
08158                                         }
08159                                 }
08160                         }
08161                 }
08162                 // init new shader vars
08163                 for (ma= main->mat.first; ma; ma= ma->id.next) {
08164                         if(ma->darkness==0.0f) {
08165                                 ma->rms=0.1f;
08166                                 ma->darkness=1.0f;
08167                         }
08168                 }
08169                 
08170                 /* softbody init new vars */
08171                 for(ob= main->object.first; ob; ob= ob->id.next) {
08172                         if(ob->soft) {
08173                                 if(ob->soft->defgoal==0.0f) ob->soft->defgoal= 0.7f;
08174                                 if(ob->soft->physics_speed==0.0f) ob->soft->physics_speed= 1.0f;
08175                                 
08176                                 if(ob->soft->interval==0) {
08177                                         ob->soft->interval= 2;
08178                                         ob->soft->sfra= 1;
08179                                         ob->soft->efra= 100;
08180                                 }
08181                         }
08182                         if(ob->soft && ob->soft->vertgroup==0) {
08183                                 bDeformGroup *locGroup = defgroup_find_name(ob, "SOFTGOAL");
08184                                 if(locGroup){
08185                                         /* retrieve index for that group */
08186                                         ob->soft->vertgroup =  1 + defgroup_find_index(ob, locGroup); 
08187                                 }
08188                         }
08189                 }
08190         }
08191         if(main->versionfile <= 237) {
08192                 bArmature *arm;
08193                 bConstraint *con;
08194                 Object *ob;
08195                 Bone *bone;
08196                 
08197                 // armature recode checks 
08198                 for(arm= main->armature.first; arm; arm= arm->id.next) {
08199                         where_is_armature(arm);
08200 
08201                         for(bone= arm->bonebase.first; bone; bone= bone->next)
08202                                 do_version_bone_head_tail_237(bone);
08203                 }
08204                 for(ob= main->object.first; ob; ob= ob->id.next) {
08205                         if(ob->parent) {
08206                                 Object *parent= newlibadr(fd, lib, ob->parent);
08207                                 if (parent && parent->type==OB_LATTICE)
08208                                         ob->partype = PARSKEL;
08209                         }
08210 
08211                         // btw. armature_rebuild_pose is further only called on leave editmode
08212                         if(ob->type==OB_ARMATURE) {
08213                                 if(ob->pose)
08214                                         ob->pose->flag |= POSE_RECALC;
08215                                 ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;       // cannot call stuff now (pointers!), done in setup_app_data
08216 
08217                                 /* new generic xray option */
08218                                 arm= newlibadr(fd, lib, ob->data);
08219                                 if(arm->flag & ARM_DRAWXRAY) {
08220                                         ob->dtx |= OB_DRAWXRAY;
08221                                 }
08222                         } else if (ob->type==OB_MESH) {
08223                                 Mesh *me = newlibadr(fd, lib, ob->data);
08224                                 
08225                                 if ((me->flag&ME_SUBSURF)) {
08226                                         SubsurfModifierData *smd = (SubsurfModifierData*) modifier_new(eModifierType_Subsurf);
08227                                         
08228                                         smd->levels = MAX2(1, me->subdiv);
08229                                         smd->renderLevels = MAX2(1, me->subdivr);
08230                                         smd->subdivType = me->subsurftype;
08231                                         
08232                                         smd->modifier.mode = 0;
08233                                         if (me->subdiv!=0)
08234                                                 smd->modifier.mode |= 1;
08235                                         if (me->subdivr!=0)
08236                                                 smd->modifier.mode |= 2;
08237                                         if (me->flag&ME_OPT_EDGES)
08238                                                 smd->flags |= eSubsurfModifierFlag_ControlEdges;
08239                                         
08240                                         BLI_addtail(&ob->modifiers, smd);
08241                                         
08242                                         modifier_unique_name(&ob->modifiers, (ModifierData*)smd);
08243                                 }
08244                         }
08245                         
08246                         // follow path constraint needs to set the 'path' option in curves...
08247                         for(con=ob->constraints.first; con; con= con->next) {
08248                                 if(con->type==CONSTRAINT_TYPE_FOLLOWPATH) {
08249                                         bFollowPathConstraint *data = con->data;
08250                                         Object *obc= newlibadr(fd, lib, data->tar);
08251                                         
08252                                         if(obc && obc->type==OB_CURVE) {
08253                                                 Curve *cu= newlibadr(fd, lib, obc->data);
08254                                                 if(cu) cu->flag |= CU_PATH;
08255                                         }
08256                                 }
08257                         }
08258                 }
08259         }
08260         if(main->versionfile <= 238) {
08261                 Lattice *lt;
08262                 Object *ob;
08263                 bArmature *arm;
08264                 Mesh *me;
08265                 Key *key;
08266                 Scene *sce= main->scene.first;
08267 
08268                 while(sce){
08269                         if(sce->toolsettings == NULL){
08270                                 sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings),"Tool Settings Struct");    
08271                                 sce->toolsettings->cornertype=0;
08272                                 sce->toolsettings->degr = 90; 
08273                                 sce->toolsettings->step = 9;
08274                                 sce->toolsettings->turn = 1;                            
08275                                 sce->toolsettings->extr_offs = 1; 
08276                                 sce->toolsettings->doublimit = 0.001f;
08277                                 sce->toolsettings->segments = 32;
08278                                 sce->toolsettings->rings = 32;
08279                                 sce->toolsettings->vertices = 32;
08280                                 sce->toolsettings->editbutflag =1;
08281                         }
08282                         sce= sce->id.next;      
08283                 }
08284 
08285                 for (lt=main->latt.first; lt; lt=lt->id.next) {
08286                         if (lt->fu==0.0f && lt->fv==0.0f && lt->fw==0.0f) {
08287                                 calc_lat_fudu(lt->flag, lt->pntsu, &lt->fu, &lt->du);
08288                                 calc_lat_fudu(lt->flag, lt->pntsv, &lt->fv, &lt->dv);
08289                                 calc_lat_fudu(lt->flag, lt->pntsw, &lt->fw, &lt->dw);
08290                         }
08291                 }
08292 
08293                 for(ob=main->object.first; ob; ob= ob->id.next) {
08294                         ModifierData *md;
08295                         PartEff *paf;
08296 
08297                         for (md=ob->modifiers.first; md; md=md->next) {
08298                                 if (md->type==eModifierType_Subsurf) {
08299                                         SubsurfModifierData *smd = (SubsurfModifierData*) md;
08300 
08301                                         smd->flags &= ~(eSubsurfModifierFlag_Incremental|eSubsurfModifierFlag_DebugIncr);
08302                                 }
08303                         }
08304 
08305                         if ((ob->softflag&OB_SB_ENABLE) && !modifiers_findByType(ob, eModifierType_Softbody)) {
08306                                 if (ob->softflag&OB_SB_POSTDEF) {
08307                                         md = ob->modifiers.first;
08308 
08309                                         while (md && modifierType_getInfo(md->type)->type==eModifierTypeType_OnlyDeform) {
08310                                                 md = md->next;
08311                                         }
08312 
08313                                         BLI_insertlinkbefore(&ob->modifiers, md, modifier_new(eModifierType_Softbody));
08314                                 } else {
08315                                         BLI_addhead(&ob->modifiers, modifier_new(eModifierType_Softbody));
08316                                 }
08317 
08318                                 ob->softflag &= ~OB_SB_ENABLE;
08319                         }
08320                         if(ob->pose) {
08321                                 bPoseChannel *pchan;
08322                                 bConstraint *con;
08323                                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
08324                                         // note, pchan->bone is also lib-link stuff
08325                                         if (pchan->limitmin[0] == 0.0f && pchan->limitmax[0] == 0.0f) {
08326                                                 pchan->limitmin[0]= pchan->limitmin[1]= pchan->limitmin[2]= -180.0f;
08327                                                 pchan->limitmax[0]= pchan->limitmax[1]= pchan->limitmax[2]= 180.0f;
08328                                                 
08329                                                 for(con= pchan->constraints.first; con; con= con->next) {
08330                                                         if(con->type == CONSTRAINT_TYPE_KINEMATIC) {
08331                                                                 bKinematicConstraint *data = (bKinematicConstraint*)con->data;
08332                                                                 data->weight = 1.0f;
08333                                                                 data->orientweight = 1.0f;
08334                                                                 data->flag &= ~CONSTRAINT_IK_ROT;
08335                                                                 
08336                                                                 /* enforce conversion from old IK_TOPARENT to rootbone index */
08337                                                                 data->rootbone= -1;
08338                                                                 
08339                                                                 /* update_pose_etc handles rootbone==-1 */
08340                                                                 ob->pose->flag |= POSE_RECALC;
08341                                                         }       
08342                                                 }
08343                                         }
08344                                 }
08345                         }
08346 
08347                         paf = give_parteff(ob);
08348                         if (paf) {
08349                                 if(paf->disp == 0)
08350                                         paf->disp = 100;
08351                                 if(paf->speedtex == 0)
08352                                         paf->speedtex = 8;
08353                                 if(paf->omat == 0)
08354                                         paf->omat = 1;
08355                         }
08356                 }
08357                 
08358                 for(arm=main->armature.first; arm; arm= arm->id.next) {
08359                         bone_version_238(&arm->bonebase);
08360                         arm->deformflag |= ARM_DEF_VGROUP;
08361                 }
08362 
08363                 for(me=main->mesh.first; me; me= me->id.next) {
08364                         if (!me->medge) {
08365                                 make_edges(me, 1);      /* 1 = use mface->edcode */
08366                         } else {
08367                                 mesh_strip_loose_faces(me);
08368                         }
08369                 }
08370                 
08371                 for(key= main->key.first; key; key= key->id.next) {
08372                         KeyBlock *kb;
08373                         int index= 1;
08374                         
08375                         /* trick to find out if we already introduced adrcode */
08376                         for(kb= key->block.first; kb; kb= kb->next)
08377                                 if(kb->adrcode) break;
08378                         
08379                         if(kb==NULL) {
08380                                 for(kb= key->block.first; kb; kb= kb->next) {
08381                                         if(kb==key->refkey) {
08382                                                 if(kb->name[0]==0)
08383                                                         strcpy(kb->name, "Basis");
08384                                         }
08385                                         else {
08386                                                 if(kb->name[0]==0)
08387                                                         sprintf(kb->name, "Key %d", index);
08388                                                 kb->adrcode= index++;
08389                                         }
08390                                 }
08391                         }
08392                 }
08393         }
08394         if(main->versionfile <= 239) {
08395                 bArmature *arm;
08396                 Object *ob;
08397                 Scene *sce= main->scene.first;
08398                 Camera *cam= main->camera.first;
08399                 Material *ma= main->mat.first;
08400                 int set_passepartout= 0;
08401                 
08402                 /* deformflag is local in modifier now */
08403                 for(ob=main->object.first; ob; ob= ob->id.next) {
08404                         ModifierData *md;
08405                         
08406                         for (md=ob->modifiers.first; md; md=md->next) {
08407                                 if (md->type==eModifierType_Armature) {
08408                                         ArmatureModifierData *amd = (ArmatureModifierData*) md;
08409                                         if(amd->object && amd->deformflag==0) {
08410                                                 Object *oba= newlibadr(fd, lib, amd->object);
08411                                                 arm= newlibadr(fd, lib, oba->data);
08412                                                 amd->deformflag= arm->deformflag;
08413                                         }
08414                                 }
08415                         }
08416                 }
08417                 
08418                 /* updating stepsize for ghost drawing */
08419                 for(arm= main->armature.first; arm; arm= arm->id.next) {
08420                         if (arm->ghostsize==0) arm->ghostsize=1;
08421                         bone_version_239(&arm->bonebase);
08422                         if(arm->layer==0) arm->layer= 1;
08423                 }
08424                 
08425                 for(;sce;sce= sce->id.next) {
08426                         /* make 'innervert' the default subdivide type, for backwards compat */
08427                         sce->toolsettings->cornertype=1;
08428                 
08429                         if(sce->r.scemode & R_PASSEPARTOUT) {
08430                                 set_passepartout= 1;
08431                                 sce->r.scemode &= ~R_PASSEPARTOUT;
08432                         }
08433                         /* gauss is filter variable now */
08434                         if(sce->r.mode & R_GAUSS) {
08435                                 sce->r.filtertype= R_FILTER_GAUSS;
08436                                 sce->r.mode &= ~R_GAUSS;
08437                         }
08438                 }
08439                 
08440                 for(;cam; cam= cam->id.next) {
08441                         if(set_passepartout)
08442                                 cam->flag |= CAM_SHOWPASSEPARTOUT;
08443                         
08444                         /* make sure old cameras have title safe on */
08445                         if (!(cam->flag & CAM_SHOWTITLESAFE))
08446                          cam->flag |= CAM_SHOWTITLESAFE;
08447                         
08448                         /* set an appropriate camera passepartout alpha */
08449                         if (!(cam->passepartalpha)) cam->passepartalpha = 0.2f;
08450                 }
08451                 
08452                 for(; ma; ma= ma->id.next) {
08453                         if(ma->strand_sta==0.0f) {
08454                                 ma->strand_sta= ma->strand_end= 1.0f;
08455                                 ma->mode |= MA_TANGENT_STR;
08456                         }
08457                         if(ma->mode & MA_TRACEBLE) ma->mode |= MA_SHADBUF;
08458                 }
08459         }
08460         
08461         if(main->versionfile <= 241) {
08462                 Object *ob;
08463                 Tex *tex;
08464                 Scene *sce;
08465                 World *wo;
08466                 Lamp *la;
08467                 Material *ma;
08468                 bArmature *arm;
08469                 bNodeTree *ntree;
08470                 
08471                 for (wo = main->world.first; wo; wo= wo->id.next) {
08472                         /* Migrate to Bullet for games, except for the NaN versions */
08473                         /* People can still explicitely choose for Sumo (after 2.42 is out) */
08474                         if(main->versionfile > 225)
08475                                 wo->physicsEngine = WOPHY_BULLET;
08476                         if(WO_AODIST == wo->aomode)
08477                                 wo->aocolor= WO_AOPLAIN;
08478                 }
08479                 
08480                 /* updating layers still */
08481                 for(arm= main->armature.first; arm; arm= arm->id.next) {
08482                         bone_version_239(&arm->bonebase);
08483                         if(arm->layer==0) arm->layer= 1;
08484                 }
08485                 for(sce= main->scene.first; sce; sce= sce->id.next) {
08486                         if(sce->audio.mixrate==0) sce->audio.mixrate= 44100;
08487 
08488                         if(sce->r.xparts<2) sce->r.xparts= 4;
08489                         if(sce->r.yparts<2) sce->r.yparts= 4;
08490                         /* adds default layer */
08491                         if(sce->r.layers.first==NULL)
08492                                 scene_add_render_layer(sce);
08493                         else {
08494                                 SceneRenderLayer *srl;
08495                                 /* new layer flag for sky, was default for solid */
08496                                 for(srl= sce->r.layers.first; srl; srl= srl->next) {
08497                                         if(srl->layflag & SCE_LAY_SOLID)
08498                                                 srl->layflag |= SCE_LAY_SKY;
08499                                         srl->passflag &= (SCE_PASS_COMBINED|SCE_PASS_Z|SCE_PASS_NORMAL|SCE_PASS_VECTOR);
08500                                 }
08501                         }
08502                         
08503                         /* node version changes */
08504                         if(sce->nodetree)
08505                                 ntree_version_241(sce->nodetree);
08506 
08507                         /* uv calculation options moved to toolsettings */
08508                         if (sce->toolsettings->uvcalc_radius == 0.0f) {
08509                                 sce->toolsettings->uvcalc_radius = 1.0f;
08510                                 sce->toolsettings->uvcalc_cubesize = 1.0f;
08511                                 sce->toolsettings->uvcalc_mapdir = 1;
08512                                 sce->toolsettings->uvcalc_mapalign = 1;
08513                                 sce->toolsettings->uvcalc_flag = UVCALC_FILLHOLES;
08514                                 sce->toolsettings->unwrapper = 1;
08515                         }
08516 
08517                         if(sce->r.mode & R_PANORAMA) {
08518                                 /* all these checks to ensure saved files with svn version keep working... */
08519                                 if(sce->r.xsch < sce->r.ysch) {
08520                                         Object *obc= newlibadr(fd, lib, sce->camera);
08521                                         if(obc && obc->type==OB_CAMERA) {
08522                                                 Camera *cam= newlibadr(fd, lib, obc->data);
08523                                                 if(cam->lens>=10.0f) {
08524                                                         sce->r.xsch*= sce->r.xparts;
08525                                                         cam->lens*= (float)sce->r.ysch/(float)sce->r.xsch;
08526                                                 }
08527                                         }
08528                                 }
08529                         }
08530                 }
08531                 
08532                 for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
08533                         ntree_version_241(ntree);
08534                 
08535                 for(la= main->lamp.first; la; la= la->id.next)
08536                         if(la->buffers==0)
08537                                 la->buffers= 1;
08538                 
08539                 for(tex= main->tex.first; tex; tex= tex->id.next) {
08540                         if(tex->env && tex->env->viewscale==0.0f)
08541                                 tex->env->viewscale= 1.0f;
08542 //                      tex->imaflag |= TEX_GAUSS_MIP;
08543                 }
08544                 
08545                 /* for empty drawsize and drawtype */
08546                 for(ob=main->object.first; ob; ob= ob->id.next) {
08547                         if(ob->empty_drawsize==0.0f) {
08548                                 ob->empty_drawtype = OB_ARROWS;
08549                                 ob->empty_drawsize = 1.0;
08550                         }
08551                 }
08552                 
08553                 for(ma= main->mat.first; ma; ma= ma->id.next) {
08554                         /* stucci returns intensity from now on */
08555                         int a;
08556                         for(a=0; a<MAX_MTEX; a++) {
08557                                 if(ma->mtex[a] && ma->mtex[a]->tex) {
08558                                         tex= newlibadr(fd, lib, ma->mtex[a]->tex);
08559                                         if(tex && tex->type==TEX_STUCCI)
08560                                                 ma->mtex[a]->mapto &= ~(MAP_COL|MAP_SPEC|MAP_REF);
08561                                 }
08562                         }
08563                         /* transmissivity defaults */
08564                         if(ma->tx_falloff==0.0f) ma->tx_falloff= 1.0f;
08565                 }
08566                 
08567                 /* during 2.41 images with this name were used for viewer node output, lets fix that */
08568                 if(main->versionfile == 241) {
08569                         Image *ima;
08570                         for(ima= main->image.first; ima; ima= ima->id.next)
08571                                 if(strcmp(ima->name, "Compositor")==0) {
08572                                         strcpy(ima->id.name+2, "Viewer Node");
08573                                         strcpy(ima->name, "Viewer Node");
08574                                 }
08575                 }
08576         }
08577                 
08578         if(main->versionfile <= 242) {
08579                 Scene *sce;
08580                 bScreen *sc;
08581                 Object *ob;
08582                 Curve *cu;
08583                 Material *ma;
08584                 Mesh *me;
08585                 Group *group;
08586                 Nurb *nu;
08587                 BezTriple *bezt;
08588                 BPoint *bp;
08589                 bNodeTree *ntree;
08590                 int a;
08591                 
08592                 for(sc= main->screen.first; sc; sc= sc->id.next) {
08593                         ScrArea *sa;
08594                         sa= sc->areabase.first;
08595                         while(sa) {
08596                                 SpaceLink *sl;
08597 
08598                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08599                                         if(sl->spacetype==SPACE_VIEW3D) {
08600                                                 View3D *v3d= (View3D*) sl;
08601                                                 if (v3d->gridsubdiv == 0)
08602                                                         v3d->gridsubdiv = 10;
08603                                         }
08604                                 }
08605                                 sa = sa->next;
08606                         }
08607                 }
08608                 
08609                 for(sce= main->scene.first; sce; sce= sce->id.next) {
08610                         if (sce->toolsettings->select_thresh == 0.0f)
08611                                 sce->toolsettings->select_thresh= 0.01f;
08612                         if (sce->toolsettings->clean_thresh == 0.0f) 
08613                                 sce->toolsettings->clean_thresh = 0.1f;
08614                                 
08615                         if (sce->r.threads==0) {
08616                                 if (sce->r.mode & R_THREADS)
08617                                         sce->r.threads= 2;
08618                                 else
08619                                         sce->r.threads= 1;
08620                         }
08621                         if(sce->nodetree)
08622                                 ntree_version_242(sce->nodetree);
08623                 }
08624                 
08625                 for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
08626                         ntree_version_242(ntree);
08627                 
08628                 /* add default radius values to old curve points */
08629                 for(cu= main->curve.first; cu; cu= cu->id.next) {
08630                         for(nu= cu->nurb.first; nu; nu= nu->next) {
08631                                 if (nu) {
08632                                         if(nu->bezt) {
08633                                                 for(bezt=nu->bezt, a=0; a<nu->pntsu; a++, bezt++) {
08634                                                         if (!bezt->radius) bezt->radius= 1.0;
08635                                                 }
08636                                         }
08637                                         else if(nu->bp) {
08638                                                 for(bp=nu->bp, a=0; a<nu->pntsu*nu->pntsv; a++, bp++) {
08639                                                         if(!bp->radius) bp->radius= 1.0;
08640                                                 }
08641                                         }
08642                                 }
08643                         }
08644                 }
08645                 
08646                 for(ob = main->object.first; ob; ob= ob->id.next) {
08647                         ModifierData *md;
08648                         ListBase *list;
08649                         list = &ob->constraints;
08650 
08651                         /* check for already existing MinMax (floor) constraint
08652                            and update the sticky flagging */
08653 
08654                         if (list){
08655                                 bConstraint *curcon;
08656                                 for (curcon = list->first; curcon; curcon=curcon->next){
08657                                         switch (curcon->type) {
08658                                                 case CONSTRAINT_TYPE_MINMAX:
08659                                                 {
08660                                                         bMinMaxConstraint *data = curcon->data;
08661                                                         if (data->sticky==1) 
08662                                                                 data->flag |= MINMAX_STICKY;
08663                                                         else 
08664                                                                 data->flag &= ~MINMAX_STICKY;
08665                                                 }
08666                                                         break;
08667                                                 case CONSTRAINT_TYPE_ROTLIKE:
08668                                                 {
08669                                                         bRotateLikeConstraint *data = curcon->data;
08670                                                         
08671                                                         /* version patch from buttons_object.c */
08672                                                         if(data->flag==0) 
08673                                                                 data->flag = ROTLIKE_X|ROTLIKE_Y|ROTLIKE_Z;
08674                                                 }
08675                                                         break;
08676                                         }
08677                                 }
08678                         }
08679 
08680                         if (ob->type == OB_ARMATURE) {
08681                                 if (ob->pose){
08682                                         bConstraint *curcon;
08683                                         bPoseChannel *pchan;
08684                                         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next){
08685                                                 for (curcon = pchan->constraints.first; curcon; curcon=curcon->next){
08686                                                         switch (curcon->type) {
08687                                                                 case CONSTRAINT_TYPE_MINMAX:
08688                                                                 {
08689                                                                         bMinMaxConstraint *data = curcon->data;
08690                                                                         if (data->sticky==1) 
08691                                                                                 data->flag |= MINMAX_STICKY;
08692                                                                         else 
08693                                                                                 data->flag &= ~MINMAX_STICKY;
08694                                                                 }
08695                                                                         break;
08696                                                                 case CONSTRAINT_TYPE_KINEMATIC:
08697                                                                 {
08698                                                                         bKinematicConstraint *data = curcon->data;
08699                                                                         if (!(data->flag & CONSTRAINT_IK_POS)) {
08700                                                                                 data->flag |= CONSTRAINT_IK_POS;
08701                                                                                 data->flag |= CONSTRAINT_IK_STRETCH;
08702                                                                         }
08703                                                                 }
08704                                                                         break;
08705                                                                 case CONSTRAINT_TYPE_ROTLIKE:
08706                                                                 {
08707                                                                         bRotateLikeConstraint *data = curcon->data;
08708                                                                         
08709                                                                         /* version patch from buttons_object.c */
08710                                                                         if(data->flag==0) 
08711                                                                                 data->flag = ROTLIKE_X|ROTLIKE_Y|ROTLIKE_Z;
08712                                                                 }
08713                                                                         break;
08714                                                         }
08715                                                 }
08716                                         }
08717                                 }
08718                         }
08719                         
08720                         /* copy old object level track settings to curve modifers */
08721                         for (md=ob->modifiers.first; md; md=md->next) {
08722                                 if (md->type==eModifierType_Curve) {
08723                                         CurveModifierData *cmd = (CurveModifierData*) md;
08724 
08725                                         if (cmd->defaxis == 0) cmd->defaxis = ob->trackflag+1;
08726                                 }
08727                         }
08728                         
08729                 }
08730                 
08731                 for(ma = main->mat.first; ma; ma= ma->id.next) {
08732                         if(ma->shad_alpha==0.0f)
08733                                 ma->shad_alpha= 1.0f;
08734                         if(ma->nodetree)
08735                                 ntree_version_242(ma->nodetree);
08736                 }
08737 
08738                 for(me=main->mesh.first; me; me=me->id.next)
08739                         customdata_version_242(me);
08740                 
08741                 for(group= main->group.first; group; group= group->id.next)
08742                         if(group->layer==0)
08743                            group->layer= (1<<20)-1;
08744                 
08745                 /* History fix (python?), shape key adrcode numbers have to be sorted */
08746                 sort_shape_fix(main);
08747                                 
08748                 /* now, subversion control! */
08749                 if(main->subversionfile < 3) {
08750                         Image *ima;
08751                         Tex *tex;
08752                         
08753                         /* Image refactor initialize */
08754                         for(ima= main->image.first; ima; ima= ima->id.next) {
08755                                 ima->source= IMA_SRC_FILE;
08756                                 ima->type= IMA_TYPE_IMAGE;
08757                                 
08758                                 ima->gen_x= 256; ima->gen_y= 256;
08759                                 ima->gen_type= 1;
08760                                 
08761                                 if(0==strncmp(ima->id.name+2, "Viewer Node", sizeof(ima->id.name)-2)) {
08762                                         ima->source= IMA_SRC_VIEWER;
08763                                         ima->type= IMA_TYPE_COMPOSITE;
08764                                 }
08765                                 if(0==strncmp(ima->id.name+2, "Render Result", sizeof(ima->id.name)-2)) {
08766                                         ima->source= IMA_SRC_VIEWER;
08767                                         ima->type= IMA_TYPE_R_RESULT;
08768                                 }
08769                                 
08770                         }
08771                         for(tex= main->tex.first; tex; tex= tex->id.next) {
08772                                 if(tex->type==TEX_IMAGE && tex->ima) {
08773                                         ima= newlibadr(fd, lib, tex->ima);
08774                                         if(tex->imaflag & TEX_ANIM5_)
08775                                                 ima->source= IMA_SRC_MOVIE;
08776                                         if(tex->imaflag & TEX_FIELDS_)
08777                                                 ima->flag |= IMA_FIELDS;
08778                                         if(tex->imaflag & TEX_STD_FIELD_)
08779                                                 ima->flag |= IMA_STD_FIELD;
08780                                 }
08781                                 tex->iuser.frames= tex->frames;
08782                                 tex->iuser.fie_ima= (char)tex->fie_ima;
08783                                 tex->iuser.offset= tex->offset;
08784                                 tex->iuser.sfra= tex->sfra;
08785                                 tex->iuser.cycl= (tex->imaflag & TEX_ANIMCYCLIC_)!=0;
08786                         }
08787                         for(sce= main->scene.first; sce; sce= sce->id.next) {
08788                                 if(sce->nodetree)
08789                                         do_version_ntree_242_2(sce->nodetree);
08790                         }
08791                         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
08792                                 do_version_ntree_242_2(ntree);
08793                         for(ma = main->mat.first; ma; ma= ma->id.next)
08794                                 if(ma->nodetree)
08795                                         do_version_ntree_242_2(ma->nodetree);
08796                         
08797                         for(sc= main->screen.first; sc; sc= sc->id.next) {
08798                                 ScrArea *sa;
08799                                 for(sa= sc->areabase.first; sa; sa= sa->next) {
08800                                         SpaceLink *sl;
08801                                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
08802                                                 if(sl->spacetype==SPACE_IMAGE)
08803                                                         ((SpaceImage *)sl)->iuser.fie_ima= 2;
08804                                                 else if(sl->spacetype==SPACE_VIEW3D) {
08805                                                         View3D *v3d= (View3D *)sl;
08806                                                         BGpic *bgpic;
08807                                                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
08808                                                                 bgpic->iuser.fie_ima= 2;
08809                                                 }
08810                                         }
08811                                 }
08812                         }
08813                 }
08814                 
08815                 if(main->subversionfile < 4) {
08816                         for(sce= main->scene.first; sce; sce= sce->id.next) {
08817                                 sce->r.bake_mode= 1;    /* prevent to include render stuff here */
08818                                 sce->r.bake_filter= 2;
08819                                 sce->r.bake_osa= 5;
08820                                 sce->r.bake_flag= R_BAKE_CLEAR;
08821                         }
08822                 }
08823 
08824                 if(main->subversionfile < 5) {
08825                         for(sce= main->scene.first; sce; sce= sce->id.next) {
08826                                 /* improved triangle to quad conversion settings */
08827                                 if(sce->toolsettings->jointrilimit==0.0f)
08828                                         sce->toolsettings->jointrilimit= 0.8f;
08829                         }
08830                 }
08831         }
08832         if(main->versionfile <= 243) {
08833                 Object *ob= main->object.first;
08834                 Material *ma;
08835 
08836                 for(ma=main->mat.first; ma; ma= ma->id.next) {
08837                         if(ma->sss_scale==0.0f) {
08838                                 ma->sss_radius[0]= 1.0f;
08839                                 ma->sss_radius[1]= 1.0f;
08840                                 ma->sss_radius[2]= 1.0f;
08841                                 ma->sss_col[0]= 0.8f;
08842                                 ma->sss_col[1]= 0.8f;
08843                                 ma->sss_col[2]= 0.8f;
08844                                 ma->sss_error= 0.05f;
08845                                 ma->sss_scale= 0.1f;
08846                                 ma->sss_ior= 1.3f;
08847                                 ma->sss_colfac= 1.0f;
08848                                 ma->sss_texfac= 0.0f;
08849                         }
08850                         if(ma->sss_front==0 && ma->sss_back==0) {
08851                                 ma->sss_front= 1.0f;
08852                                 ma->sss_back= 1.0f;
08853                         }
08854                         if(ma->sss_col[0]==0 && ma->sss_col[1]==0 && ma->sss_col[2]==0) {
08855                                 ma->sss_col[0]= ma->r;
08856                                 ma->sss_col[1]= ma->g;
08857                                 ma->sss_col[2]= ma->b;
08858                         }
08859                 }
08860                 
08861                 for(; ob; ob= ob->id.next) {
08862                         bDeformGroup *curdef;
08863                         
08864                         for(curdef= ob->defbase.first; curdef; curdef=curdef->next) {
08865                                 /* replace an empty-string name with unique name */
08866                                 if (curdef->name[0] == '\0') {
08867                                         defgroup_unique_name(curdef, ob);
08868                                 }
08869                         }
08870 
08871                         if(main->versionfile < 243 || main->subversionfile < 1) {
08872                                 ModifierData *md;
08873 
08874                                 /* translate old mirror modifier axis values to new flags */
08875                                 for (md=ob->modifiers.first; md; md=md->next) {
08876                                         if (md->type==eModifierType_Mirror) {
08877                                                 MirrorModifierData *mmd = (MirrorModifierData*) md;
08878 
08879                                                 switch(mmd->axis)
08880                                                 {
08881                                                 case 0:
08882                                                         mmd->flag |= MOD_MIR_AXIS_X;
08883                                                         break;
08884                                                 case 1:
08885                                                         mmd->flag |= MOD_MIR_AXIS_Y;
08886                                                         break;
08887                                                 case 2:
08888                                                         mmd->flag |= MOD_MIR_AXIS_Z;
08889                                                         break;
08890                                                 }
08891 
08892                                                 mmd->axis = 0;
08893                                         }
08894                                 }
08895                         }
08896                 }
08897                 
08898                 /* render layer added, this is not the active layer */
08899                 if(main->versionfile <= 243 || main->subversionfile < 2) {
08900                         Mesh *me;
08901                         for(me=main->mesh.first; me; me=me->id.next)
08902                                 customdata_version_243(me);
08903                 }               
08904 
08905         }
08906         
08907         if(main->versionfile <= 244) {
08908                 Scene *sce;
08909                 bScreen *sc;
08910                 Lamp *la;
08911                 World *wrld;
08912                 
08913                 if(main->versionfile != 244 || main->subversionfile < 2) {
08914                         for(sce= main->scene.first; sce; sce= sce->id.next)
08915                                 sce->r.mode |= R_SSS;
08916 
08917                         /* correct older action editors - incorrect scrolling */
08918                         for(sc= main->screen.first; sc; sc= sc->id.next) {
08919                                 ScrArea *sa;
08920                                 sa= sc->areabase.first;
08921                                 while(sa) {
08922                                         SpaceLink *sl;
08923 
08924                                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
08925                                                 if(sl->spacetype==SPACE_ACTION) {
08926                                                         SpaceAction *saction= (SpaceAction*) sl;
08927                                                         
08928                                                         saction->v2d.tot.ymin= -1000.0;
08929                                                         saction->v2d.tot.ymax= 0.0;
08930                                                         
08931                                                         saction->v2d.cur.ymin= -75.0;
08932                                                         saction->v2d.cur.ymax= 5.0;
08933                                                 }
08934                                         }
08935                                         sa = sa->next;
08936                                 }
08937                         }
08938                 }
08939                 if (main->versionfile != 244 || main->subversionfile < 3) {     
08940                         /* constraints recode version patch used to be here. Moved to 245 now... */
08941                         
08942                         
08943                         for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
08944                                 if (wrld->mode & WO_AMB_OCC)
08945                                         wrld->ao_samp_method = WO_AOSAMP_CONSTANT;
08946                                 else
08947                                         wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY;
08948                                 
08949                                 wrld->ao_adapt_thresh = 0.005f;
08950                         }
08951                         
08952                         for(la=main->lamp.first; la; la= la->id.next) {
08953                                 if (la->type == LA_AREA)
08954                                         la->ray_samp_method = LA_SAMP_CONSTANT;
08955                                 else
08956                                         la->ray_samp_method = LA_SAMP_HALTON;
08957                                 
08958                                 la->adapt_thresh = 0.001f;
08959                         }
08960                 }
08961         }
08962         if(main->versionfile <= 245) {
08963                 Scene *sce;
08964                 bScreen *sc;
08965                 Object *ob;
08966                 Image *ima;
08967                 Lamp *la;
08968                 Material *ma;
08969                 ParticleSettings *part;
08970                 World *wrld;
08971                 Mesh *me;
08972                 bNodeTree *ntree;
08973                 Tex *tex;
08974                 ModifierData *md;
08975                 ParticleSystem *psys;
08976                 
08977                 /* unless the file was created 2.44.3 but not 2.45, update the constraints */
08978                 if ( !(main->versionfile==244 && main->subversionfile==3) &&
08979                          ((main->versionfile<245) || (main->versionfile==245 && main->subversionfile==0)) ) 
08980                 {
08981                         for (ob = main->object.first; ob; ob= ob->id.next) {
08982                                 ListBase *list;
08983                                 list = &ob->constraints;
08984                                 
08985                                 /* fix up constraints due to constraint recode changes (originally at 2.44.3) */
08986                                 if (list) {
08987                                         bConstraint *curcon;
08988                                         for (curcon = list->first; curcon; curcon=curcon->next) {
08989                                                 /* old CONSTRAINT_LOCAL check -> convert to CONSTRAINT_SPACE_LOCAL */
08990                                                 if (curcon->flag & 0x20) {
08991                                                         curcon->ownspace = CONSTRAINT_SPACE_LOCAL;
08992                                                         curcon->tarspace = CONSTRAINT_SPACE_LOCAL;
08993                                                 }
08994                                                 
08995                                                 switch (curcon->type) {
08996                                                         case CONSTRAINT_TYPE_LOCLIMIT:
08997                                                         {
08998                                                                 bLocLimitConstraint *data= (bLocLimitConstraint *)curcon->data;
08999                                                                 
09000                                                                 /* old limit without parent option for objects */
09001                                                                 if (data->flag2)
09002                                                                         curcon->ownspace = CONSTRAINT_SPACE_LOCAL;
09003                                                         }
09004                                                                 break;
09005                                                 }       
09006                                         }
09007                                 }
09008                                 
09009                                 /* correctly initialise constinv matrix */
09010                                 unit_m4(ob->constinv);
09011                                 
09012                                 if (ob->type == OB_ARMATURE) {
09013                                         if (ob->pose) {
09014                                                 bConstraint *curcon;
09015                                                 bPoseChannel *pchan;
09016                                                 
09017                                                 for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
09018                                                         /* make sure constraints are all up to date */
09019                                                         for (curcon = pchan->constraints.first; curcon; curcon=curcon->next) {
09020                                                                 /* old CONSTRAINT_LOCAL check -> convert to CONSTRAINT_SPACE_LOCAL */
09021                                                                 if (curcon->flag & 0x20) {
09022                                                                         curcon->ownspace = CONSTRAINT_SPACE_LOCAL;
09023                                                                         curcon->tarspace = CONSTRAINT_SPACE_LOCAL;
09024                                                                 }
09025                                                                 
09026                                                                 switch (curcon->type) {
09027                                                                         case CONSTRAINT_TYPE_ACTION:
09028                                                                         {
09029                                                                                 bActionConstraint *data= (bActionConstraint *)curcon->data;
09030                                                                                 
09031                                                                                 /* 'data->local' used to mean that target was in local-space */
09032                                                                                 if (data->local)
09033                                                                                         curcon->tarspace = CONSTRAINT_SPACE_LOCAL;
09034                                                                         }                                                       
09035                                                                                 break;
09036                                                                 }
09037                                                         }
09038                                                         
09039                                                         /* correctly initialise constinv matrix */
09040                                                         unit_m4(pchan->constinv);
09041                                                 }
09042                                         }
09043                                 }
09044                         }
09045                 }
09046                 
09047                 /* fix all versions before 2.45 */
09048                 if (main->versionfile != 245) {
09049 
09050                         /* repair preview from 242 - 244*/
09051                         for(ima= main->image.first; ima; ima= ima->id.next) {
09052                                 ima->preview = NULL;
09053                         }
09054                         
09055                         /* repair imasel space - completely reworked */
09056                         for(sc= main->screen.first; sc; sc= sc->id.next) {
09057                                 ScrArea *sa;
09058                                 sa= sc->areabase.first;
09059                                 while(sa) {
09060                                         SpaceLink *sl;
09061                                         
09062                                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
09063                                                 if(sl->spacetype==SPACE_IMASEL) {
09064                                                         SpaceImaSel *simasel= (SpaceImaSel*) sl;
09065                                                         simasel->blockscale= 0.7f;
09066                                                         /* view 2D */
09067                                                         simasel->v2d.tot.xmin=  -10.0f;
09068                                                         simasel->v2d.tot.ymin=  -10.0f;
09069                                                         simasel->v2d.tot.xmax= (float)sa->winx + 10.0f;
09070                                                         simasel->v2d.tot.ymax= (float)sa->winy + 10.0f;                                         
09071                                                         simasel->v2d.cur.xmin=  0.0f;
09072                                                         simasel->v2d.cur.ymin=  0.0f;
09073                                                         simasel->v2d.cur.xmax= (float)sa->winx;
09074                                                         simasel->v2d.cur.ymax= (float)sa->winy;                                         
09075                                                         simasel->v2d.min[0]= 1.0;
09076                                                         simasel->v2d.min[1]= 1.0;                                               
09077                                                         simasel->v2d.max[0]= 32000.0f;
09078                                                         simasel->v2d.max[1]= 32000.0f;                                          
09079                                                         simasel->v2d.minzoom= 0.5f;
09080                                                         simasel->v2d.maxzoom= 1.21f;                                            
09081                                                         simasel->v2d.scroll= 0;
09082                                                         simasel->v2d.keepzoom= V2D_LIMITZOOM|V2D_KEEPASPECT;
09083                                                         simasel->v2d.keeptot= 0;
09084                                                         simasel->prv_h = 96;
09085                                                         simasel->prv_w = 96;
09086                                                         simasel->flag = 7; /* ??? elubie */
09087                                                         strcpy (simasel->dir,  U.textudir);     /* TON */
09088                                                         strcpy (simasel->file, "");
09089                                                         
09090                                                         simasel->returnfunc     =  NULL;
09091                                                         simasel->title[0]       =  0;
09092                                                 }
09093                                         }
09094                                         sa = sa->next;
09095                                 }
09096                         }
09097                 }
09098 
09099                 /* add point caches */
09100                 for(ob=main->object.first; ob; ob=ob->id.next) {
09101                         if(ob->soft && !ob->soft->pointcache)
09102                                 ob->soft->pointcache= BKE_ptcache_add(&ob->soft->ptcaches);
09103 
09104                         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
09105                                 if(psys->pointcache) {
09106                                         if(psys->pointcache->flag & PTCACHE_BAKED && (psys->pointcache->flag & PTCACHE_DISK_CACHE)==0) {
09107                                                 printf("Old memory cache isn't supported for particles, so re-bake the simulation!\n");
09108                                                 psys->pointcache->flag &= ~PTCACHE_BAKED;
09109                                         }
09110                                 }
09111                                 else
09112                                         psys->pointcache= BKE_ptcache_add(&psys->ptcaches);
09113                         }
09114 
09115                         for(md=ob->modifiers.first; md; md=md->next) {
09116                                 if(md->type==eModifierType_Cloth) {
09117                                         ClothModifierData *clmd = (ClothModifierData*) md;
09118                                         if(!clmd->point_cache)
09119                                                 clmd->point_cache= BKE_ptcache_add(&clmd->ptcaches);
09120                                 }
09121                         }
09122                 }
09123 
09124                 /* Copy over old per-level multires vertex data
09125                    into a single vertex array in struct Multires */
09126                 for(me = main->mesh.first; me; me=me->id.next) {
09127                         if(me->mr && !me->mr->verts) {
09128                                 MultiresLevel *lvl = me->mr->levels.last;
09129                                 if(lvl) {
09130                                         me->mr->verts = lvl->verts;
09131                                         lvl->verts = NULL;
09132                                         /* Don't need the other vert arrays */
09133                                         for(lvl = lvl->prev; lvl; lvl = lvl->prev) {
09134                                                 MEM_freeN(lvl->verts);
09135                                                 lvl->verts = NULL;
09136                                         }
09137                                 }
09138                         }
09139                 }
09140                 
09141                 if (main->versionfile != 245 || main->subversionfile < 1) {
09142                         for(la=main->lamp.first; la; la= la->id.next) {
09143                                 if (la->mode & LA_QUAD) la->falloff_type = LA_FALLOFF_SLIDERS;
09144                                 else la->falloff_type = LA_FALLOFF_INVLINEAR;
09145                                 
09146                                 if (la->curfalloff == NULL) {
09147                                         la->curfalloff = curvemapping_add(1, 0.0f, 1.0f, 1.0f, 0.0f);
09148                                         curvemapping_initialize(la->curfalloff);
09149                                 }
09150                         }
09151                 }               
09152                 
09153                 for(ma=main->mat.first; ma; ma= ma->id.next) {
09154                         if(ma->samp_gloss_mir == 0) {
09155                                 ma->gloss_mir = ma->gloss_tra= 1.0f;
09156                                 ma->aniso_gloss_mir = 1.0f;
09157                                 ma->samp_gloss_mir = ma->samp_gloss_tra= 18;
09158                                 ma->adapt_thresh_mir = ma->adapt_thresh_tra = 0.005f;
09159                                 ma->dist_mir = 0.0f;
09160                                 ma->fadeto_mir = MA_RAYMIR_FADETOSKY;
09161                         }
09162 
09163                         if(ma->strand_min == 0.0f)
09164                                 ma->strand_min= 1.0f;
09165                 }
09166 
09167                 for(part=main->particle.first; part; part=part->id.next) {
09168                         if(part->ren_child_nbr==0)
09169                                 part->ren_child_nbr= part->child_nbr;
09170 
09171                         if(part->simplify_refsize==0) {
09172                                 part->simplify_refsize= 1920;
09173                                 part->simplify_rate= 1.0f;
09174                                 part->simplify_transition= 0.1f;
09175                                 part->simplify_viewport= 0.8f;
09176                         }
09177                 }
09178 
09179                 for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
09180                         if(wrld->ao_approx_error == 0.0f)
09181                                 wrld->ao_approx_error= 0.25f;
09182                 }
09183 
09184                 for(sce= main->scene.first; sce; sce= sce->id.next) {
09185                         if(sce->nodetree)
09186                                 ntree_version_245(fd, lib, sce->nodetree);
09187 
09188                         if(sce->r.simplify_shadowsamples == 0) {
09189                                 sce->r.simplify_subsurf= 6;
09190                                 sce->r.simplify_particles= 1.0f;
09191                                 sce->r.simplify_shadowsamples= 16;
09192                                 sce->r.simplify_aosss= 1.0f;
09193                         }
09194 
09195                         if(sce->r.cineongamma == 0) {
09196                                 sce->r.cineonblack= 95;
09197                                 sce->r.cineonwhite= 685;
09198                                 sce->r.cineongamma= 1.7f;
09199                         }
09200                 }
09201 
09202                 for(ntree=main->nodetree.first; ntree; ntree= ntree->id.next)
09203                         ntree_version_245(fd, lib, ntree);
09204 
09205                 /* fix for temporary flag changes during 245 cycle */
09206                 for(ima= main->image.first; ima; ima= ima->id.next) {
09207                         if(ima->flag & IMA_OLD_PREMUL) {
09208                                 ima->flag &= ~IMA_OLD_PREMUL;
09209                                 ima->flag |= IMA_DO_PREMUL;
09210                         }
09211                 }
09212 
09213                 for(tex=main->tex.first; tex; tex=tex->id.next) {
09214                         if(tex->iuser.flag & IMA_OLD_PREMUL) {
09215                                 tex->iuser.flag &= ~IMA_OLD_PREMUL;
09216                                 tex->iuser.flag |= IMA_DO_PREMUL;
09217 
09218                         }
09219 
09220                         ima= newlibadr(fd, lib, tex->ima);
09221                         if(ima && (tex->iuser.flag & IMA_DO_PREMUL)) { 
09222                                 ima->flag &= ~IMA_OLD_PREMUL;
09223                                 ima->flag |= IMA_DO_PREMUL;
09224                         }
09225                 }
09226         }
09227         
09228         /* sanity check for skgen
09229          * */
09230         {
09231                 Scene *sce;
09232                 for(sce=main->scene.first; sce; sce = sce->id.next)
09233                 {
09234                         if (sce->toolsettings->skgen_subdivisions[0] == sce->toolsettings->skgen_subdivisions[1] ||
09235                                 sce->toolsettings->skgen_subdivisions[0] == sce->toolsettings->skgen_subdivisions[2] ||
09236                                 sce->toolsettings->skgen_subdivisions[1] == sce->toolsettings->skgen_subdivisions[2])
09237                         {
09238                                         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
09239                                         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
09240                                         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
09241                         }
09242                 }
09243         }
09244         
09245 
09246         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 2)) {
09247                 Image *ima;
09248 
09249                 /* initialize 1:1 Aspect */
09250                 for(ima= main->image.first; ima; ima= ima->id.next) {
09251                         ima->aspx = ima->aspy = 1.0f;                           
09252                 }
09253 
09254         }
09255 
09256         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 4)) {
09257                 bArmature *arm;
09258                 ModifierData *md;
09259                 Object *ob;
09260                 
09261                 for(arm= main->armature.first; arm; arm= arm->id.next)
09262                         arm->deformflag |= ARM_DEF_B_BONE_REST;
09263                 
09264                 for(ob = main->object.first; ob; ob= ob->id.next) {
09265                         for(md=ob->modifiers.first; md; md=md->next) {
09266                                 if(md->type==eModifierType_Armature)
09267                                         ((ArmatureModifierData*)md)->deformflag |= ARM_DEF_B_BONE_REST;
09268                         }
09269                 }
09270         }
09271 
09272         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 5)) {
09273                 /* foreground color needs to be somthing other then black */
09274                 Scene *sce;
09275                 for(sce= main->scene.first; sce; sce=sce->id.next) {
09276                         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
09277                         sce->r.fg_stamp[3] = 1.0f; /* dont use text alpha yet */
09278                         sce->r.bg_stamp[3] = 0.25f; /* make sure the background has full alpha */
09279                 }
09280         }
09281 
09282         
09283         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 6)) {
09284                 Scene *sce;
09285                 /* fix frs_sec_base */
09286                 for(sce= main->scene.first; sce; sce= sce->id.next) {
09287                         if (sce->r.frs_sec_base == 0) {
09288                                 sce->r.frs_sec_base = 1;
09289                         }
09290                 }
09291         }
09292         
09293         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 7)) {
09294                 Object *ob;
09295                 bPoseChannel *pchan;
09296                 bConstraint *con;
09297                 bConstraintTarget *ct;
09298                 
09299                 for (ob = main->object.first; ob; ob= ob->id.next) {
09300                         if (ob->pose) {
09301                                 for (pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
09302                                         for (con=pchan->constraints.first; con; con=con->next) {
09303                                                 if (con->type == CONSTRAINT_TYPE_PYTHON) {
09304                                                         bPythonConstraint *data= (bPythonConstraint *)con->data;
09305                                                         if (data->tar) {
09306                                                                 /* version patching needs to be done */
09307                                                                 ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
09308                                                                 
09309                                                                 ct->tar = data->tar;
09310                                                                 strcpy(ct->subtarget, data->subtarget);
09311                                                                 ct->space = con->tarspace;
09312                                                                 
09313                                                                 BLI_addtail(&data->targets, ct);
09314                                                                 data->tarnum++;
09315                                                                 
09316                                                                 /* clear old targets to avoid problems */
09317                                                                 data->tar = NULL;
09318                                                                 strcpy(data->subtarget, "");
09319                                                         }
09320                                                 }
09321                                                 else if (con->type == CONSTRAINT_TYPE_LOCLIKE) {
09322                                                         bLocateLikeConstraint *data= (bLocateLikeConstraint *)con->data;
09323                                                         
09324                                                         /* new headtail functionality makes Bone-Tip function obsolete */
09325                                                         if (data->flag & LOCLIKE_TIP)
09326                                                                 con->headtail = 1.0f;
09327                                                 }
09328                                         }
09329                                 }
09330                         }
09331                         
09332                         for (con=ob->constraints.first; con; con=con->next) {
09333                                 if (con->type==CONSTRAINT_TYPE_PYTHON) {
09334                                         bPythonConstraint *data= (bPythonConstraint *)con->data;
09335                                         if (data->tar) {
09336                                                 /* version patching needs to be done */
09337                                                 ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
09338                                                 
09339                                                 ct->tar = data->tar;
09340                                                 strcpy(ct->subtarget, data->subtarget);
09341                                                 ct->space = con->tarspace;
09342                                                 
09343                                                 BLI_addtail(&data->targets, ct);
09344                                                 data->tarnum++;
09345                                                 
09346                                                 /* clear old targets to avoid problems */
09347                                                 data->tar = NULL;
09348                                                 strcpy(data->subtarget, "");
09349                                         }
09350                                 }
09351                                 else if (con->type == CONSTRAINT_TYPE_LOCLIKE) {
09352                                         bLocateLikeConstraint *data= (bLocateLikeConstraint *)con->data;
09353                                         
09354                                         /* new headtail functionality makes Bone-Tip function obsolete */
09355                                         if (data->flag & LOCLIKE_TIP)
09356                                                 con->headtail = 1.0f;
09357                                 }
09358                         }
09359 
09360                         if(ob->soft && ob->soft->keys) {
09361                                 SoftBody *sb = ob->soft;
09362                                 int k;
09363 
09364                                 for(k=0; k<sb->totkey; k++) {
09365                                         if(sb->keys[k])
09366                                                 MEM_freeN(sb->keys[k]);
09367                                 }
09368 
09369                                 MEM_freeN(sb->keys);
09370 
09371                                 sb->keys = NULL;
09372                                 sb->totkey = 0;
09373                         }
09374                 }
09375         }
09376 
09377         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 8)) {
09378                 Scene *sce;
09379                 Object *ob;
09380                 PartEff *paf=NULL;
09381 
09382                 for(ob = main->object.first; ob; ob= ob->id.next) {
09383                         if(ob->soft && ob->soft->keys) {
09384                                 SoftBody *sb = ob->soft;
09385                                 int k;
09386 
09387                                 for(k=0; k<sb->totkey; k++) {
09388                                         if(sb->keys[k])
09389                                                 MEM_freeN(sb->keys[k]);
09390                                 }
09391 
09392                                 MEM_freeN(sb->keys);
09393 
09394                                 sb->keys = NULL;
09395                                 sb->totkey = 0;
09396                         }
09397 
09398                         /* convert old particles to new system */
09399                         if((paf = give_parteff(ob))) {
09400                                 ParticleSystem *psys;
09401                                 ModifierData *md;
09402                                 ParticleSystemModifierData *psmd;
09403                                 ParticleSettings *part;
09404 
09405                                 /* create new particle system */
09406                                 psys = MEM_callocN(sizeof(ParticleSystem), "particle_system");
09407                                 psys->pointcache = BKE_ptcache_add(&psys->ptcaches);
09408 
09409                                 part = psys->part = psys_new_settings("ParticleSettings", main);
09410                                 
09411                                 /* needed for proper libdata lookup */
09412                                 oldnewmap_insert(fd->libmap, psys->part, psys->part, 0);
09413                                 part->id.lib= ob->id.lib;
09414 
09415                                 part->id.us--;
09416                                 part->id.flag |= (ob->id.flag & LIB_NEEDLINK);
09417                                 
09418                                 psys->totpart=0;
09419                                 psys->flag= PSYS_ENABLED|PSYS_CURRENT;
09420 
09421                                 BLI_addtail(&ob->particlesystem, psys);
09422 
09423                                 md= modifier_new(eModifierType_ParticleSystem);
09424                                 sprintf(md->name, "ParticleSystem %i", BLI_countlist(&ob->particlesystem));
09425                                 psmd= (ParticleSystemModifierData*) md;
09426                                 psmd->psys=psys;
09427                                 BLI_addtail(&ob->modifiers, md);
09428 
09429                                 /* convert settings from old particle system */
09430                                 /* general settings */
09431                                 part->totpart = MIN2(paf->totpart, 100000);
09432                                 part->sta = paf->sta;
09433                                 part->end = paf->end;
09434                                 part->lifetime = paf->lifetime;
09435                                 part->randlife = paf->randlife;
09436                                 psys->seed = paf->seed;
09437                                 part->disp = paf->disp;
09438                                 part->omat = paf->mat[0];
09439                                 part->hair_step = paf->totkey;
09440 
09441                                 part->eff_group = paf->group;
09442 
09443                                 /* old system didn't interpolate between keypoints at render time */
09444                                 part->draw_step = part->ren_step = 0;
09445 
09446                                 /* physics */
09447                                 part->normfac = paf->normfac * 25.0f;
09448                                 part->obfac = paf->obfac;
09449                                 part->randfac = paf->randfac * 25.0f;
09450                                 part->dampfac = paf->damp;
09451                                 VECCOPY(part->acc, paf->force);
09452 
09453                                 /* flags */
09454                                 if(paf->stype & PAF_VECT) {
09455                                         if(paf->flag & PAF_STATIC) {
09456                                                 /* new hair lifetime is always 100.0f */
09457                                                 float fac = paf->lifetime / 100.0f;
09458 
09459                                                 part->draw_as = PART_DRAW_PATH;
09460                                                 part->type = PART_HAIR;
09461                                                 psys->recalc |= PSYS_RECALC_REDO;
09462 
09463                                                 part->normfac *= fac;
09464                                                 part->randfac *= fac;
09465                                         }
09466                                         else {
09467                                                 part->draw_as = PART_DRAW_LINE;
09468                                                 part->draw |= PART_DRAW_VEL_LENGTH;
09469                                                 part->draw_line[1] = 0.04f;
09470                                         }
09471                                 }
09472 
09473                                 part->rotmode = PART_ROT_VEL;
09474                                 
09475                                 part->flag |= (paf->flag & PAF_BSPLINE) ? PART_HAIR_BSPLINE : 0;
09476                                 part->flag |= (paf->flag & PAF_TRAND) ? PART_TRAND : 0;
09477                                 part->flag |= (paf->flag & PAF_EDISTR) ? PART_EDISTR : 0;
09478                                 part->flag |= (paf->flag & PAF_UNBORN) ? PART_UNBORN : 0;
09479                                 part->flag |= (paf->flag & PAF_DIED) ? PART_DIED : 0;
09480                                 part->from |= (paf->flag & PAF_FACE) ? PART_FROM_FACE : 0;
09481                                 part->draw |= (paf->flag & PAF_SHOWE) ? PART_DRAW_EMITTER : 0;
09482 
09483                                 psys->vgroup[PSYS_VG_DENSITY] = paf->vertgroup;
09484                                 psys->vgroup[PSYS_VG_VEL] = paf->vertgroup_v;
09485                                 psys->vgroup[PSYS_VG_LENGTH] = paf->vertgroup_v;
09486 
09487                                 /* dupliobjects */
09488                                 if(ob->transflag & OB_DUPLIVERTS) {
09489                                         Object *dup = main->object.first;
09490 
09491                                         for(; dup; dup= dup->id.next) {
09492                                                 if(ob == newlibadr(fd, lib, dup->parent)) {
09493                                                         part->dup_ob = dup;
09494                                                         ob->transflag |= OB_DUPLIPARTS;
09495                                                         ob->transflag &= ~OB_DUPLIVERTS;
09496 
09497                                                         part->draw_as = PART_DRAW_OB;
09498 
09499                                                         /* needed for proper libdata lookup */
09500                                                         oldnewmap_insert(fd->libmap, dup, dup, 0);
09501                                                 }
09502                                         }
09503                                 }
09504 
09505                                 
09506                                 {
09507                                         FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
09508                                         if(fluidmd && fluidmd->fss && fluidmd->fss->type == OB_FLUIDSIM_PARTICLE)
09509                                                 part->type = PART_FLUID;
09510                                 }
09511 
09512                                 free_effects(&ob->effect);
09513 
09514                                 printf("Old particle system converted to new system.\n");
09515                         }
09516                 }
09517 
09518                 for(sce= main->scene.first; sce; sce=sce->id.next) {
09519                         ParticleEditSettings *pset= &sce->toolsettings->particle;
09520                         int a;
09521 
09522                         if(pset->brush[0].size == 0) {
09523                                 pset->flag= PE_KEEP_LENGTHS|PE_LOCK_FIRST|PE_DEFLECT_EMITTER;
09524                                 pset->emitterdist= 0.25f;
09525                                 pset->totrekey= 5;
09526                                 pset->totaddkey= 5;
09527                                 pset->brushtype= PE_BRUSH_NONE;
09528 
09529                                 for(a=0; a<PE_TOT_BRUSH; a++) {
09530                                         pset->brush[a].strength= 50;
09531                                         pset->brush[a].size= 50;
09532                                         pset->brush[a].step= 10;
09533                                 }
09534 
09535                                 pset->brush[PE_BRUSH_CUT].strength= 100;
09536                         }
09537                 }
09538         }
09539         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 9)) {
09540                 Material *ma;
09541                 int a;
09542 
09543                 for(ma=main->mat.first; ma; ma= ma->id.next)
09544                         if(ma->mode & MA_NORMAP_TANG)
09545                                 for(a=0; a<MAX_MTEX; a++)
09546                                         if(ma->mtex[a] && ma->mtex[a]->tex)
09547                                                 ma->mtex[a]->normapspace = MTEX_NSPACE_TANGENT;
09548         }
09549         
09550         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 10)) {
09551                 Object *ob;
09552                 
09553                 /* dupliface scale */
09554                 for(ob= main->object.first; ob; ob= ob->id.next)
09555                         ob->dupfacesca = 1.0f;
09556         }
09557         
09558         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 11)) {
09559                 Object *ob;
09560                 bActionStrip *strip;
09561                 
09562                 /* nla-strips - scale */                
09563                 for (ob= main->object.first; ob; ob= ob->id.next) {
09564                         for (strip= ob->nlastrips.first; strip; strip= strip->next) {
09565                                 float length, actlength, repeat;
09566                                 
09567                                 if (strip->flag & ACTSTRIP_USESTRIDE)
09568                                         repeat= 1.0f;
09569                                 else
09570                                         repeat= strip->repeat;
09571                                 
09572                                 length = strip->end-strip->start;
09573                                 if (length == 0.0f) length= 1.0f;
09574                                 actlength = strip->actend-strip->actstart;
09575                                 
09576                                 strip->scale = length / (repeat * actlength);
09577                                 if (strip->scale == 0.0f) strip->scale= 1.0f;
09578                         }       
09579                         if(ob->soft){
09580                                 ob->soft->inpush =  ob->soft->inspring;
09581                                 ob->soft->shearstiff = 1.0f; 
09582                         }
09583                 }
09584         }
09585 
09586         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 14)) {
09587                 Scene *sce;
09588                 Sequence *seq;
09589                 
09590                 for(sce=main->scene.first; sce; sce=sce->id.next) {
09591                         SEQ_BEGIN(sce->ed, seq) {
09592                                 if (seq->blend_mode == 0)
09593                                         seq->blend_opacity = 100.0f;
09594                         }
09595                         SEQ_END
09596                 }
09597         }
09598         
09599         /*fix broken group lengths in id properties*/
09600         if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 15)) {
09601                 idproperties_fix_group_lengths(main->scene);
09602                 idproperties_fix_group_lengths(main->library);
09603                 idproperties_fix_group_lengths(main->object);
09604                 idproperties_fix_group_lengths(main->mesh);
09605                 idproperties_fix_group_lengths(main->curve);
09606                 idproperties_fix_group_lengths(main->mball);
09607                 idproperties_fix_group_lengths(main->mat);
09608                 idproperties_fix_group_lengths(main->tex);
09609                 idproperties_fix_group_lengths(main->image);
09610                 idproperties_fix_group_lengths(main->latt);
09611                 idproperties_fix_group_lengths(main->lamp);
09612                 idproperties_fix_group_lengths(main->camera);
09613                 idproperties_fix_group_lengths(main->ipo);
09614                 idproperties_fix_group_lengths(main->key);
09615                 idproperties_fix_group_lengths(main->world);
09616                 idproperties_fix_group_lengths(main->screen);
09617                 idproperties_fix_group_lengths(main->script);
09618                 idproperties_fix_group_lengths(main->vfont);
09619                 idproperties_fix_group_lengths(main->text);
09620                 idproperties_fix_group_lengths(main->sound);
09621                 idproperties_fix_group_lengths(main->group);
09622                 idproperties_fix_group_lengths(main->armature);
09623                 idproperties_fix_group_lengths(main->action);
09624                 idproperties_fix_group_lengths(main->nodetree);
09625                 idproperties_fix_group_lengths(main->brush);
09626                 idproperties_fix_group_lengths(main->particle);         
09627         }
09628 
09629         /* sun/sky */
09630         if(main->versionfile < 246) {
09631                 Object *ob;
09632                 bActuator *act;
09633 
09634                 /* dRot actuator change direction in 2.46 */
09635                 for(ob = main->object.first; ob; ob= ob->id.next) {
09636                         for(act= ob->actuators.first; act; act= act->next) {
09637                                 if (act->type == ACT_OBJECT) {
09638                                         bObjectActuator *ba= act->data;
09639 
09640                                         ba->drot[0] = -ba->drot[0];
09641                                         ba->drot[1] = -ba->drot[1];
09642                                         ba->drot[2] = -ba->drot[2];
09643                                 }
09644                         }
09645                 }
09646         }
09647         
09648         // convert fluids to modifier
09649         if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1))
09650         {
09651                 Object *ob;
09652                 
09653                 for(ob = main->object.first; ob; ob= ob->id.next) {
09654                         if(ob->fluidsimSettings)
09655                         {
09656                                 FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifier_new(eModifierType_Fluidsim);
09657                                 BLI_addhead(&ob->modifiers, (ModifierData *)fluidmd);
09658                                 
09659                                 MEM_freeN(fluidmd->fss);
09660                                 fluidmd->fss = MEM_dupallocN(ob->fluidsimSettings);
09661                                 fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
09662                                 MEM_freeN(ob->fluidsimSettings);
09663                                 
09664                                 fluidmd->fss->lastgoodframe = INT_MAX;
09665                                 fluidmd->fss->flag = 0;
09666                                 fluidmd->fss->meshVelocities = NULL;
09667                         }
09668                 }
09669         }
09670         
09671 
09672         if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)) {
09673                 Mesh *me;
09674 
09675                 for(me=main->mesh.first; me; me= me->id.next)
09676                         alphasort_version_246(fd, lib, me);
09677         }
09678         
09679         if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)){
09680                 Object *ob;
09681                 for(ob = main->object.first; ob; ob= ob->id.next) {
09682                         if(ob->pd && (ob->pd->forcefield == PFIELD_WIND))
09683                                 ob->pd->f_noise = 0.0f;
09684                 }
09685         }
09686 
09687         if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 2)){
09688                 Object *ob;
09689                 for(ob = main->object.first; ob; ob= ob->id.next) {
09690                         ob->gameflag |= OB_COLLISION;
09691                         ob->margin = 0.06f;
09692                 }
09693         }
09694 
09695         if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 3)){
09696                 Object *ob;
09697                 for(ob = main->object.first; ob; ob= ob->id.next) {
09698                         // Starting from subversion 3, ACTOR is a separate feature.
09699                         // Before it was conditioning all the other dynamic flags
09700                         if (!(ob->gameflag & OB_ACTOR))
09701                                 ob->gameflag &= ~(OB_GHOST|OB_DYNAMIC|OB_RIGID_BODY|OB_SOFT_BODY|OB_COLLISION_RESPONSE);
09702                         /* suitable default for older files */
09703                 }
09704         }
09705 
09706         if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 5)) {
09707                 Lamp *la= main->lamp.first;
09708                 for(; la; la= la->id.next) {
09709                         la->skyblendtype= MA_RAMP_ADD;
09710                         la->skyblendfac= 1.0f;
09711                 }
09712         }
09713         
09714         /* set the curve radius interpolation to 2.47 default - easy */
09715         if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 6)) {
09716                 Curve *cu;
09717                 Nurb *nu;
09718                 
09719                 for(cu= main->curve.first; cu; cu= cu->id.next) {
09720                         for(nu= cu->nurb.first; nu; nu= nu->next) {
09721                                 if (nu) {
09722                                         nu->radius_interp = 3;
09723                                         
09724                                         /* resolu and resolv are now used differently for surfaces
09725                                          * rather than using the resolution to define the entire number of divisions,
09726                                          * use it for the number of divisions per segment
09727                                          */
09728                                         if (nu->pntsv > 1) {
09729                                                 nu->resolu = MAX2( 1, (int)(((float)nu->resolu / (float)nu->pntsu)+0.5f) );
09730                                                 nu->resolv = MAX2( 1, (int)(((float)nu->resolv / (float)nu->pntsv)+0.5f) );
09731                                         }
09732                                 }
09733                         }
09734                 }
09735         }
09736         /* direction constraint actuators were always local in previous version */
09737         if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 7)) {
09738                 bActuator *act;
09739                 Object *ob;
09740                 
09741                 for(ob = main->object.first; ob; ob= ob->id.next) {
09742                         for(act= ob->actuators.first; act; act= act->next) {
09743                                 if (act->type == ACT_CONSTRAINT) {
09744                                         bConstraintActuator *coa = act->data;
09745                                         if (coa->type == ACT_CONST_TYPE_DIST) {
09746                                                 coa->flag |= ACT_CONST_LOCAL;
09747                                         }
09748                                 }
09749                         }
09750                 }
09751         }
09752 
09753         if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 9)) {
09754                 Lamp *la= main->lamp.first;
09755                 for(; la; la= la->id.next) {
09756                         la->sky_exposure= 1.0f;
09757                 }
09758         }
09759         
09760         /* BGE message actuators needed OB prefix, very confusing */
09761         if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 10)) {
09762                 bActuator *act;
09763                 Object *ob;
09764                 
09765                 for(ob = main->object.first; ob; ob= ob->id.next) {
09766                         for(act= ob->actuators.first; act; act= act->next) {
09767                                 if (act->type == ACT_MESSAGE) {
09768                                         bMessageActuator *msgAct = (bMessageActuator *) act->data;
09769                                         if (BLI_strnlen(msgAct->toPropName, 3) > 2) {
09770                                                 /* strip first 2 chars, would have only worked if these were OB anyway */
09771                                                 memmove( msgAct->toPropName, msgAct->toPropName+2, sizeof(msgAct->toPropName)-2 );
09772                                         } else {
09773                                                 msgAct->toPropName[0] = '\0';
09774                                         }
09775                                 }
09776                         }
09777                 }
09778         }
09779 
09780         if (main->versionfile < 248) {
09781                 Lamp *la;
09782 
09783                 for(la=main->lamp.first; la; la= la->id.next) {
09784                         if(la->atm_turbidity == 0.0f) {
09785                                 la->sun_effect_type = 0;
09786                                 la->horizon_brightness = 1.0f;
09787                                 la->spread = 1.0f;
09788                                 la->sun_brightness = 1.0f;
09789                                 la->sun_size = 1.0f;
09790                                 la->backscattered_light = 1.0f;
09791                                 la->atm_turbidity = 2.0f;
09792                                 la->atm_inscattering_factor = 1.0f;
09793                                 la->atm_extinction_factor = 1.0f;
09794                                 la->atm_distance_factor = 1.0f;
09795                                 la->sun_intensity = 1.0f;
09796                         }
09797                 }
09798         }
09799 
09800         if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 2)) {
09801                 Scene *sce;
09802                 
09803                 /* Note, these will need to be added for painting */
09804                 for (sce= main->scene.first; sce; sce= sce->id.next) {
09805                         sce->toolsettings->imapaint.seam_bleed = 2;
09806                         sce->toolsettings->imapaint.normal_angle = 80;
09807 
09808                         /* initialize skeleton generation toolsettings */
09809                         sce->toolsettings->skgen_resolution = 250;
09810                         sce->toolsettings->skgen_threshold_internal     = 0.1f;
09811                         sce->toolsettings->skgen_threshold_external     = 0.1f;
09812                         sce->toolsettings->skgen_angle_limit                    = 30.0f;
09813                         sce->toolsettings->skgen_length_ratio                   = 1.3f;
09814                         sce->toolsettings->skgen_length_limit                   = 1.5f;
09815                         sce->toolsettings->skgen_correlation_limit              = 0.98f;
09816                         sce->toolsettings->skgen_symmetry_limit                 = 0.1f;
09817                         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
09818                         sce->toolsettings->skgen_postpro_passes = 3;
09819                         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL|SKGEN_FILTER_EXTERNAL|SKGEN_FILTER_SMART|SKGEN_SUB_CORRELATION|SKGEN_HARMONIC;
09820                         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
09821                         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
09822                         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
09823 
09824                         
09825                         sce->toolsettings->skgen_retarget_angle_weight = 1.0f;
09826                         sce->toolsettings->skgen_retarget_length_weight = 1.0f;
09827                         sce->toolsettings->skgen_retarget_distance_weight = 1.0f;
09828         
09829                         /* Skeleton Sketching */
09830                         sce->toolsettings->bone_sketching = 0;
09831                         sce->toolsettings->skgen_retarget_roll = SK_RETARGET_ROLL_VIEW;
09832                 }
09833         }
09834         if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 3)) {
09835                 bScreen *sc;
09836                 
09837                 /* adjust default settings for Animation Editors */
09838                 for (sc= main->screen.first; sc; sc= sc->id.next) {
09839                         ScrArea *sa;
09840                         
09841                         for (sa= sc->areabase.first; sa; sa= sa->next) { 
09842                                 SpaceLink *sl;
09843                                 
09844                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
09845                                         switch (sl->spacetype) {
09846                                                 case SPACE_ACTION:
09847                                                 {
09848                                                         SpaceAction *sact= (SpaceAction *)sl;
09849                                                         
09850                                                         sact->mode= SACTCONT_DOPESHEET;
09851                                                         sact->autosnap= SACTSNAP_FRAME;
09852                                                 }
09853                                                         break;
09854                                                 case SPACE_IPO:
09855                                                 {
09856                                                         SpaceIpo *sipo= (SpaceIpo *)sl;
09857                                                         sipo->autosnap= SACTSNAP_FRAME;
09858                                                 }
09859                                                         break;
09860                                                 case SPACE_NLA:
09861                                                 {
09862                                                         SpaceNla *snla= (SpaceNla *)sl;
09863                                                         snla->autosnap= SACTSNAP_FRAME;
09864                                                 }
09865                                                         break;
09866                                         }
09867                                 }
09868                         }
09869                 }
09870         }
09871 
09872         if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 3)) {
09873                 Object *ob;
09874 
09875                 /* Adjustments needed after Bullets update */
09876                 for(ob = main->object.first; ob; ob= ob->id.next) {
09877                         ob->damping *= 0.635f;
09878                         ob->rdamping = 0.1f + (0.8f * ob->rdamping);
09879                 }
09880         }
09881         
09882         if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 4)) {
09883                 Scene *sce;
09884                 World *wrld;
09885 
09886                 /*  Dome (Fisheye) default parameters  */
09887                 for (sce= main->scene.first; sce; sce= sce->id.next) {
09888                         sce->r.domeangle = 180;
09889                         sce->r.domemode = 1;
09890                         sce->r.domeres = 4;
09891                         sce->r.domeresbuf = 1.0f;
09892                         sce->r.dometilt = 0;
09893                 }
09894                 /* DBVT culling by default */
09895                 for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
09896                         wrld->mode |= WO_DBVT_CULLING;
09897                         wrld->occlusionRes = 128;
09898                 }
09899         }
09900 
09901         if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 5)) {
09902                 Object *ob;
09903                 World *wrld;
09904                 for(ob = main->object.first; ob; ob= ob->id.next) {
09905                         ob->m_contactProcessingThreshold = 1.; //pad3 is used for m_contactProcessingThreshold
09906                         if(ob->parent) {
09907                                 /* check if top parent has compound shape set and if yes, set this object
09908                                    to compound shaper as well (was the behaviour before, now it's optional) */
09909                                 Object *parent= newlibadr(fd, lib, ob->parent);
09910                                 while (parent && parent != ob &&  parent->parent != NULL) {
09911                                         parent = newlibadr(fd, lib, parent->parent);
09912                                 }
09913                                 if(parent) {
09914                                         if (parent->gameflag & OB_CHILD)
09915                                                 ob->gameflag |= OB_CHILD;
09916                                 }
09917                         }
09918                 }
09919                 for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
09920                         wrld->ticrate = 60;
09921                         wrld->maxlogicstep = 5;
09922                         wrld->physubstep = 1;
09923                         wrld->maxphystep = 5;
09924                 }
09925         }
09926 
09927         if (main->versionfile < 249) {
09928                 Scene *sce;
09929                 for (sce= main->scene.first; sce; sce= sce->id.next)
09930                         sce->r.renderer= 0;
09931                 
09932         }
09933         
09934         // correct introduce of seed for wind force
09935         if (main->versionfile < 249 && main->subversionfile < 1) {
09936                 Object *ob;
09937                 for(ob = main->object.first; ob; ob= ob->id.next) {
09938                         if(ob->pd)
09939                                 ob->pd->seed = ((unsigned int)(ceil(PIL_check_seconds_timer()))+1) % 128;
09940                 }
09941         
09942         }
09943 
09944         if (main->versionfile < 249 && main->subversionfile < 2) {
09945                 Scene *sce= main->scene.first;
09946                 Sequence *seq;
09947                 Editing *ed;
09948                 
09949                 while(sce) {
09950                         ed= sce->ed;
09951                         if(ed) {
09952                                 SEQP_BEGIN(ed, seq) {
09953                                         if (seq->strip && seq->strip->proxy){
09954                                                 if (sce->r.size != 100.0) {
09955                                                         seq->strip->proxy->size
09956                                                                 = sce->r.size;
09957                                                 } else {
09958                                                         seq->strip->proxy->size = 25;
09959                                                 }
09960                                                 seq->strip->proxy->quality =90;
09961                                         }
09962                                 }
09963                                 SEQ_END
09964                         }
09965                         
09966                         sce= sce->id.next;
09967                 }
09968 
09969         }
09970 
09971         if (main->versionfile < 250) {
09972                 bScreen *screen;
09973                 Scene *scene;
09974                 Base *base;
09975                 Material *ma;
09976                 Camera *cam;
09977                 Mesh *me;
09978                 Curve *cu;
09979                 Scene *sce;
09980                 Tex *tx;
09981                 ParticleSettings *part;
09982                 Object *ob;
09983                 //PTCacheID *pid;
09984                 //ListBase pidlist;
09985 
09986                 bSound *sound;
09987                 Sequence *seq;
09988                 bActuator *act;
09989                 int a;
09990 
09991                 for(sound = main->sound.first; sound; sound = sound->id.next)
09992                 {
09993                         if(sound->newpackedfile)
09994                         {
09995                                 sound->packedfile = sound->newpackedfile;
09996                                 sound->newpackedfile = NULL;
09997                         }
09998                 }
09999 
10000                 for(ob = main->object.first; ob; ob= ob->id.next) {
10001                         for(act= ob->actuators.first; act; act= act->next) {
10002                                 if (act->type == ACT_SOUND) {
10003                                         bSoundActuator *sAct = (bSoundActuator*) act->data;
10004                                         if(sAct->sound)
10005                                         {
10006                                                 sound = newlibadr(fd, lib, sAct->sound);
10007                                                 sAct->flag = sound->flags & SOUND_FLAGS_3D ? ACT_SND_3D_SOUND : 0;
10008                                                 sAct->pitch = sound->pitch;
10009                                                 sAct->volume = sound->volume;
10010                                                 sAct->sound3D.reference_distance = sound->distance;
10011                                                 sAct->sound3D.max_gain = sound->max_gain;
10012                                                 sAct->sound3D.min_gain = sound->min_gain;
10013                                                 sAct->sound3D.rolloff_factor = sound->attenuation;
10014                                         }
10015                                         else
10016                                         {
10017                                                 sAct->sound3D.reference_distance = 1.0f;
10018                                                 sAct->volume = 1.0f;
10019                                                 sAct->sound3D.max_gain = 1.0f;
10020                                                 sAct->sound3D.rolloff_factor = 1.0f;
10021                                         }
10022                                         sAct->sound3D.cone_inner_angle = 360.0f;
10023                                         sAct->sound3D.cone_outer_angle = 360.0f;
10024                                         sAct->sound3D.max_distance = FLT_MAX;
10025                                 }
10026                         }
10027                 }
10028 
10029                 for(scene = main->scene.first; scene; scene = scene->id.next)
10030                 {
10031                         if(scene->ed && scene->ed->seqbasep)
10032                         {
10033                                 for(seq = scene->ed->seqbasep->first; seq; seq = seq->next)
10034                                 {
10035                                         if(seq->type == SEQ_HD_SOUND)
10036                                         {
10037                                                 char str[FILE_MAX];
10038                                                 BLI_join_dirfile(str, sizeof(str), seq->strip->dir, seq->strip->stripdata->name);
10039                                                 BLI_path_abs(str, main->name);
10040                                                 seq->sound = sound_new_file(main, str);
10041                                         }
10042                                         /* don't know, if anybody used that
10043                                            this way, but just in case, upgrade
10044                                            to new way... */
10045                                         if((seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) &&
10046                                            !(seq->flag & SEQ_USE_PROXY_CUSTOM_DIR))
10047                                         {
10048                                                 
10049                                                 snprintf(seq->strip->proxy->dir, 
10050                                                          FILE_MAXDIR, "%s/BL_proxy", 
10051                                                          seq->strip->dir);
10052                                         }
10053                                 }
10054                         }
10055                 }
10056 
10057                 for(screen= main->screen.first; screen; screen= screen->id.next) {
10058                         do_versions_windowmanager_2_50(screen);
10059                         do_versions_gpencil_2_50(main, screen);
10060                 }
10061                 
10062                 /* shader, composit and texture node trees have id.name empty, put something in
10063                  * to have them show in RNA viewer and accessible otherwise.
10064                  */
10065                 for(ma= main->mat.first; ma; ma= ma->id.next) {
10066                         if(ma->nodetree && strlen(ma->nodetree->id.name)==0)
10067                                 strcpy(ma->nodetree->id.name, "NTShader Nodetree");
10068                         
10069                         /* which_output 0 is now "not specified" */
10070                         for(a=0; a<MAX_MTEX; a++) {
10071                                 if(ma->mtex[a]) {
10072                                         tx= newlibadr(fd, lib, ma->mtex[a]->tex);
10073                                         if(tx && tx->use_nodes)
10074                                                 ma->mtex[a]->which_output++;
10075                                 }
10076                         }
10077                 }
10078                 /* and composit trees */
10079                 for(sce= main->scene.first; sce; sce= sce->id.next) {
10080                         if(sce->nodetree && strlen(sce->nodetree->id.name)==0)
10081                                 strcpy(sce->nodetree->id.name, "NTCompositing Nodetree");
10082 
10083                         /* move to cameras */
10084                         if(sce->r.mode & R_PANORAMA) {
10085                                 for(base=sce->base.first; base; base=base->next) {
10086                                         ob= newlibadr(fd, lib, base->object);
10087 
10088                                         if(ob->type == OB_CAMERA && !ob->id.lib) {
10089                                                 cam= newlibadr(fd, lib, ob->data);
10090                                                 cam->flag |= CAM_PANORAMA;
10091                                         }
10092                                 }
10093 
10094                                 sce->r.mode &= ~R_PANORAMA;
10095                         }
10096                 }
10097                 /* and texture trees */
10098                 for(tx= main->tex.first; tx; tx= tx->id.next) {
10099                         bNode *node;
10100 
10101                         if(tx->nodetree) {
10102                                 if(strlen(tx->nodetree->id.name)==0)
10103                                         strcpy(tx->nodetree->id.name, "NTTexture Nodetree");
10104 
10105                                 /* which_output 0 is now "not specified" */
10106                                 for(node=tx->nodetree->nodes.first; node; node=node->next)
10107                                         if(node->type == TEX_NODE_OUTPUT)
10108                                                 node->custom1++;
10109                         }
10110                 }
10111                 
10112                 /* copy standard draw flag to meshes(used to be global, is not available here) */
10113                 for(me= main->mesh.first; me; me= me->id.next) {
10114                         me->drawflag= ME_DRAWEDGES|ME_DRAWFACES|ME_DRAWCREASES;
10115                 }
10116 
10117                 /* particle draw and render types */
10118                 for(part= main->particle.first; part; part= part->id.next) {
10119                         if(part->draw_as) {
10120                                 if(part->draw_as == PART_DRAW_DOT) {
10121                                         part->ren_as = PART_DRAW_HALO;
10122                                         part->draw_as = PART_DRAW_REND;
10123                                 }
10124                                 else if(part->draw_as <= PART_DRAW_AXIS) {
10125                                         part->ren_as = PART_DRAW_HALO;
10126                                 }
10127                                 else {
10128                                         part->ren_as = part->draw_as;
10129                                         part->draw_as = PART_DRAW_REND;
10130                                 }
10131                         }
10132                         part->path_end = 1.0f;
10133                         part->clength = 1.0f;
10134                 }
10135                 /* set old pointcaches to have disk cache flag */
10136                 for(ob = main->object.first; ob; ob= ob->id.next) {
10137 
10138                         //BKE_ptcache_ids_from_object(&pidlist, ob);
10139 
10140                         //for(pid=pidlist.first; pid; pid=pid->next)
10141                         //      pid->cache->flag |= PTCACHE_DISK_CACHE;
10142 
10143                         //BLI_freelistN(&pidlist);
10144                 }
10145 
10146                 /* type was a mixed flag & enum. move the 2d flag elsewhere */
10147                 for(cu = main->curve.first; cu; cu= cu->id.next) {
10148                         Nurb *nu;
10149 
10150                         for(nu= cu->nurb.first; nu; nu= nu->next) {
10151                                 nu->flag |= (nu->type & CU_2D);
10152                                 nu->type &= CU_TYPE;
10153                         }
10154                 }
10155         }
10156 
10157         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 1)) {
10158                 Object *ob;
10159                 Material *ma;
10160                 Tex *tex;
10161                 Scene *sce;
10162                 ToolSettings *ts;
10163                 //PTCacheID *pid;
10164                 //ListBase pidlist;
10165 
10166                 for(ob = main->object.first; ob; ob = ob->id.next) {
10167                         //BKE_ptcache_ids_from_object(&pidlist, ob);
10168 
10169                         //for(pid=pidlist.first; pid; pid=pid->next) {
10170                         //      if(pid->ptcaches->first == NULL)
10171                         //              pid->ptcaches->first = pid->ptcaches->last = pid->cache;
10172                         //}
10173 
10174                         //BLI_freelistN(&pidlist);
10175 
10176                         if(ob->type == OB_MESH) {
10177                                 Mesh *me = newlibadr(fd, lib, ob->data);
10178                                 void *olddata = ob->data;
10179                                 ob->data = me;
10180 
10181                                 if(me && me->id.lib==NULL && me->mr && me->mr->level_count > 1) /* XXX - library meshes crash on loading most yoFrankie levels, the multires pointer gets invalid -  Campbell */
10182                                         multires_load_old(ob, me);
10183 
10184                                 ob->data = olddata;
10185                         }
10186 
10187                         if(ob->totcol && ob->matbits == NULL) {
10188                                 int a;
10189 
10190                                 ob->matbits= MEM_callocN(sizeof(char)*ob->totcol, "ob->matbits");
10191                                 for(a=0; a<ob->totcol; a++)
10192                                         ob->matbits[a]= ob->colbits & (1<<a);
10193                         }
10194                 }
10195 
10196                 /* texture filter */
10197                 for(tex = main->tex.first; tex; tex = tex->id.next) {
10198                         if(tex->afmax == 0)
10199                                 tex->afmax= 8;
10200                 }
10201 
10202                 for(ma = main->mat.first; ma; ma = ma->id.next) {
10203                         int a;
10204                         if(ma->mode & MA_WIRE) {
10205                                 ma->material_type= MA_TYPE_WIRE;
10206                                 ma->mode &= ~MA_WIRE;
10207                         }
10208                         if(ma->mode & MA_HALO) {
10209                                 ma->material_type= MA_TYPE_HALO;
10210                                 ma->mode &= ~MA_HALO;
10211                         }
10212 
10213                         if(ma->mode & (MA_ZTRANSP|MA_RAYTRANSP)) {
10214                                 ma->mode |= MA_TRANSP;
10215                         }
10216                         else {
10217                                 ma->mode |= MA_ZTRANSP;
10218                                 ma->mode &= ~MA_TRANSP;
10219                         }
10220 
10221                         /* set new bump for unused slots */
10222                         for(a=0; a<MAX_MTEX; a++) {
10223                                 if(ma->mtex[a]) {
10224                                         tex= ma->mtex[a]->tex;
10225                                         if(!tex) {
10226                                                 ma->mtex[a]->texflag |= MTEX_3TAP_BUMP;
10227                                                 ma->mtex[a]->texflag |= MTEX_BUMP_OBJECTSPACE;
10228                                         } else {
10229                                                 tex= (Tex*)newlibadr(fd, ma->id.lib, tex);
10230                                                 if(tex && tex->type == 0) { /* invalid type */
10231                                                         ma->mtex[a]->texflag |= MTEX_3TAP_BUMP;
10232                                                         ma->mtex[a]->texflag |= MTEX_BUMP_OBJECTSPACE;
10233                                                 }
10234                                         }
10235                                 }
10236                         }
10237                         
10238                         /* volume rendering settings */
10239                         if (ma->vol.stepsize < 0.0001f) {
10240                                 ma->vol.density = 1.0f;
10241                                 ma->vol.emission = 0.0f;
10242                                 ma->vol.scattering = 1.0f;
10243                                 ma->vol.emission_col[0] = ma->vol.emission_col[1] = ma->vol.emission_col[2] = 1.0f;
10244                                 ma->vol.density_scale = 1.0f;
10245                                 ma->vol.depth_cutoff = 0.01f;
10246                                 ma->vol.stepsize_type = MA_VOL_STEP_RANDOMIZED;
10247                                 ma->vol.stepsize = 0.2f;
10248                                 ma->vol.shade_type = MA_VOL_SHADE_SHADED;
10249                                 ma->vol.shadeflag |= MA_VOL_PRECACHESHADING;
10250                                 ma->vol.precache_resolution = 50;
10251                         }
10252                 }
10253 
10254                 for(sce = main->scene.first; sce; sce = sce->id.next) {
10255                         ts= sce->toolsettings;
10256                         if(ts->normalsize == 0.0f || !ts->uv_selectmode || ts->vgroup_weight == 0.0f) {
10257                                 ts->normalsize= 0.1f;
10258                                 ts->selectmode= SCE_SELECT_VERTEX;
10259                                 
10260                                 /* autokeying - setting should be taken from the user-prefs
10261                                  * but the userprefs version may not have correct flags set 
10262                                  * (i.e. will result in blank box when enabled)
10263                                  */
10264                                 ts->autokey_mode= U.autokey_mode;
10265                                 if (ts->autokey_mode == 0) 
10266                                         ts->autokey_mode= 2; /* 'add/replace' but not on */
10267                                 ts->uv_selectmode= UV_SELECT_VERTEX;
10268                                 ts->vgroup_weight= 1.0f;
10269                         }
10270 
10271                         /* Game Settings */
10272                         //Dome
10273                         sce->gm.dome.angle = sce->r.domeangle;
10274                         sce->gm.dome.mode = sce->r.domemode;
10275                         sce->gm.dome.res = sce->r.domeres;
10276                         sce->gm.dome.resbuf = sce->r.domeresbuf;
10277                         sce->gm.dome.tilt = sce->r.dometilt;
10278                         sce->gm.dome.warptext = sce->r.dometext;
10279 
10280                         //Stand Alone
10281                         sce->gm.fullscreen = sce->r.fullscreen;
10282                         sce->gm.xplay = sce->r.xplay;
10283                         sce->gm.yplay = sce->r.yplay;
10284                         sce->gm.freqplay = sce->r.freqplay;
10285                         sce->gm.depth = sce->r.depth;
10286                         sce->gm.attrib = sce->r.attrib;
10287 
10288                         //Stereo
10289                         sce->gm.stereomode = sce->r.stereomode;
10290                         /* reassigning stereomode NO_STEREO and DOME to a separeted flag*/
10291                         if (sce->gm.stereomode == 1){ //1 = STEREO_NOSTEREO
10292                                 sce->gm.stereoflag = STEREO_NOSTEREO;
10293                                 sce->gm.stereomode = STEREO_ANAGLYPH;
10294                         }
10295                         else if(sce->gm.stereomode == 8){ //8 = STEREO_DOME
10296                                 sce->gm.stereoflag = STEREO_DOME;
10297                                 sce->gm.stereomode = STEREO_ANAGLYPH;
10298                         }
10299                         else
10300                                 sce->gm.stereoflag = STEREO_ENABLED;
10301 
10302                         //Framing
10303                         sce->gm.framing = sce->framing;
10304                         sce->gm.xplay = sce->r.xplay;
10305                         sce->gm.yplay = sce->r.yplay;
10306                         sce->gm.freqplay= sce->r.freqplay;
10307                         sce->gm.depth= sce->r.depth;
10308 
10309                         //Physic (previously stored in world)
10310                         sce->gm.gravity =9.8f;
10311                         sce->gm.physicsEngine= WOPHY_BULLET;// Bullet by default
10312                         sce->gm.mode = WO_DBVT_CULLING; // DBVT culling by default
10313                         sce->gm.occlusionRes = 128;
10314                         sce->gm.ticrate = 60;
10315                         sce->gm.maxlogicstep = 5;
10316                         sce->gm.physubstep = 1;
10317                         sce->gm.maxphystep = 5;
10318                 }
10319         }
10320 
10321         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 2)) {
10322                 Scene *sce;
10323                 Object *ob;
10324 
10325                 for(sce = main->scene.first; sce; sce = sce->id.next) {
10326                         if(fd->fileflags & G_FILE_ENABLE_ALL_FRAMES)
10327                                 sce->gm.flag |= GAME_ENABLE_ALL_FRAMES;
10328                         if(fd->fileflags & G_FILE_SHOW_DEBUG_PROPS)
10329                                 sce->gm.flag |= GAME_SHOW_DEBUG_PROPS;
10330                         if(fd->fileflags & G_FILE_SHOW_FRAMERATE)
10331                                 sce->gm.flag |= GAME_SHOW_FRAMERATE;
10332                         if(fd->fileflags & G_FILE_SHOW_PHYSICS)
10333                                 sce->gm.flag |= GAME_SHOW_PHYSICS;
10334                         if(fd->fileflags & G_FILE_GLSL_NO_SHADOWS)
10335                                 sce->gm.flag |= GAME_GLSL_NO_SHADOWS;
10336                         if(fd->fileflags & G_FILE_GLSL_NO_SHADERS)
10337                                 sce->gm.flag |= GAME_GLSL_NO_SHADERS;
10338                         if(fd->fileflags & G_FILE_GLSL_NO_RAMPS)
10339                                 sce->gm.flag |= GAME_GLSL_NO_RAMPS;
10340                         if(fd->fileflags & G_FILE_GLSL_NO_NODES)
10341                                 sce->gm.flag |= GAME_GLSL_NO_NODES;
10342                         if(fd->fileflags & G_FILE_GLSL_NO_EXTRA_TEX)
10343                                 sce->gm.flag |= GAME_GLSL_NO_EXTRA_TEX;
10344                         if(fd->fileflags & G_FILE_IGNORE_DEPRECATION_WARNINGS)
10345                                 sce->gm.flag |= GAME_IGNORE_DEPRECATION_WARNINGS;
10346 
10347                         if(fd->fileflags & G_FILE_GAME_MAT_GLSL)
10348                                 sce->gm.matmode= GAME_MAT_GLSL;
10349                         else if(fd->fileflags & G_FILE_GAME_MAT)
10350                                 sce->gm.matmode= GAME_MAT_MULTITEX;
10351                         else
10352                                 sce->gm.matmode= GAME_MAT_TEXFACE;
10353 
10354                         sce->gm.flag |= GAME_DISPLAY_LISTS;
10355                 }
10356                 
10357                 for(ob = main->object.first; ob; ob = ob->id.next) {
10358                         if(ob->flag & 8192) // OB_POSEMODE = 8192
10359                                 ob->mode |= OB_MODE_POSE;
10360                 }
10361         }
10362 
10363         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 4)) {
10364                 Scene *sce;
10365                 Object *ob;
10366                 Material *ma;
10367                 Lamp *la;
10368                 World *wo;
10369                 Tex *tex;
10370                 ParticleSettings *part;
10371                 int do_gravity = 0;
10372 
10373                 for(sce = main->scene.first; sce; sce = sce->id.next)
10374                         if(sce->unit.scale_length == 0.0f)
10375                                 sce->unit.scale_length= 1.0f;
10376                 
10377                 for(ob = main->object.first; ob; ob = ob->id.next) {
10378                         /* fluid-sim stuff */
10379                         FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
10380                         if (fluidmd) fluidmd->fss->fmd = fluidmd;
10381                         
10382                         /* rotation modes were added, but old objects would now default to being 'quaternion based' */
10383                         ob->rotmode= ROT_MODE_EUL;
10384                 }
10385                 
10386                 for(ma = main->mat.first; ma; ma=ma->id.next) {
10387                         if(ma->vol.reflection == 0.f) {
10388                                 ma->vol.reflection = 1.f;
10389                                 ma->vol.transmission_col[0] = ma->vol.transmission_col[1] = ma->vol.transmission_col[2] = 1.0f;
10390                                 ma->vol.reflection_col[0] = ma->vol.reflection_col[1] = ma->vol.reflection_col[2] = 1.0f;
10391                         }
10392 
10393                         do_version_mtex_factor_2_50(ma->mtex, ID_MA);
10394                 }
10395 
10396                 for(la = main->lamp.first; la; la=la->id.next)
10397                         do_version_mtex_factor_2_50(la->mtex, ID_LA);
10398 
10399                 for(wo = main->world.first; wo; wo=wo->id.next)
10400                         do_version_mtex_factor_2_50(wo->mtex, ID_WO);
10401 
10402                 for(tex = main->tex.first; tex; tex=tex->id.next)
10403                         if(tex->vd)
10404                                 if(tex->vd->extend == 0)
10405                                         tex->vd->extend = TEX_CLIP;
10406                 
10407                 for(sce= main->scene.first; sce; sce= sce->id.next)
10408                 {
10409                         if(sce->audio.main == 0.0f)
10410                                 sce->audio.main = 1.0f;
10411 
10412                         sce->r.ffcodecdata.audio_mixrate = sce->audio.mixrate;
10413                         sce->r.ffcodecdata.audio_volume = sce->audio.main;
10414                         sce->audio.distance_model = 2;
10415                         sce->audio.doppler_factor = 1.0f;
10416                         sce->audio.speed_of_sound = 343.3f;
10417                 }
10418 
10419                 /* Add default gravity to scenes */
10420                 for(sce= main->scene.first; sce; sce= sce->id.next) {
10421                         if((sce->physics_settings.flag & PHYS_GLOBAL_GRAVITY) == 0
10422                                 && len_v3(sce->physics_settings.gravity) == 0.0f) {
10423 
10424                                 sce->physics_settings.gravity[0] = sce->physics_settings.gravity[1] = 0.0f;
10425                                 sce->physics_settings.gravity[2] = -9.81f;
10426                                 sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
10427                                 do_gravity = 1;
10428                         }
10429                 }
10430 
10431                 /* Assign proper global gravity weights for dynamics (only z-coordinate is taken into account) */
10432                 if(do_gravity) for(part= main->particle.first; part; part= part->id.next)
10433                         part->effector_weights->global_gravity = part->acc[2]/-9.81f;
10434 
10435                 for(ob = main->object.first; ob; ob = ob->id.next) {
10436                         ModifierData *md;
10437 
10438                         if(do_gravity) {
10439                                 for(md= ob->modifiers.first; md; md= md->next) {
10440                                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
10441                                         if(clmd)
10442                                                 clmd->sim_parms->effector_weights->global_gravity = clmd->sim_parms->gravity[2]/-9.81f;
10443                                 }
10444 
10445                                 if(ob->soft)
10446                                         ob->soft->effector_weights->global_gravity = ob->soft->grav/9.81f;
10447                         }
10448 
10449                         /* Normal wind shape is plane */
10450                         if(ob->pd) {
10451                                 if(ob->pd->forcefield == PFIELD_WIND)
10452                                         ob->pd->shape = PFIELD_SHAPE_PLANE;
10453                                 
10454                                 if(ob->pd->flag & PFIELD_PLANAR)
10455                                         ob->pd->shape = PFIELD_SHAPE_PLANE;
10456                                 else if(ob->pd->flag & PFIELD_SURFACE)
10457                                         ob->pd->shape = PFIELD_SHAPE_SURFACE;
10458 
10459                                 ob->pd->flag |= PFIELD_DO_LOCATION;
10460                         }
10461                 }
10462         }
10463 
10464         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 6)) {
10465                 Object *ob;
10466                 Lamp *la;
10467                 
10468                 /* New variables for axis-angle rotations and/or quaternion rotations were added, and need proper initialisation */
10469                 for (ob= main->object.first; ob; ob= ob->id.next) {
10470                         /* new variables for all objects */
10471                         ob->quat[0]= 1.0f;
10472                         ob->rotAxis[1]= 1.0f;
10473                         
10474                         /* bones */
10475                         if (ob->pose) {
10476                                 bPoseChannel *pchan;
10477                                 
10478                                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
10479                                         /* just need to initalise rotation axis properly... */
10480                                         pchan->rotAxis[1]= 1.0f;
10481                                 }
10482                         }
10483                 }
10484 
10485                 for(la = main->lamp.first; la; la=la->id.next)
10486                         la->compressthresh= 0.05f;
10487         }
10488 
10489         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 7)) {
10490                 Mesh *me;
10491                 Nurb *nu;
10492                 Lattice *lt;
10493                 Curve *cu;
10494                 Key *key;
10495                 float *data;
10496                 int a, tot;
10497 
10498                 /* shape keys are no longer applied to the mesh itself, but rather
10499                    to the derivedmesh/displist, so here we ensure that the basis
10500                    shape key is always set in the mesh coordinates. */
10501 
10502                 for(me= main->mesh.first; me; me= me->id.next) {
10503                         if((key = newlibadr(fd, lib, me->key)) && key->refkey) {
10504                                 data= key->refkey->data;
10505                                 tot= MIN2(me->totvert, key->refkey->totelem);
10506 
10507                                 for(a=0; a<tot; a++, data+=3)
10508                                         VECCOPY(me->mvert[a].co, data)
10509                         }
10510                 }
10511 
10512                 for(lt= main->latt.first; lt; lt= lt->id.next) {
10513                         if((key = newlibadr(fd, lib, lt->key)) && key->refkey) {
10514                                 data= key->refkey->data;
10515                                 tot= MIN2(lt->pntsu*lt->pntsv*lt->pntsw, key->refkey->totelem);
10516 
10517                                 for(a=0; a<tot; a++, data+=3)
10518                                         VECCOPY(lt->def[a].vec, data)
10519                         }
10520                 }
10521 
10522                 for(cu= main->curve.first; cu; cu= cu->id.next) {
10523                         if((key = newlibadr(fd, lib, cu->key)) && key->refkey) {
10524                                 data= key->refkey->data;
10525 
10526                                 for(nu=cu->nurb.first; nu; nu=nu->next) {
10527                                         if(nu->bezt) {
10528                                                 BezTriple *bezt = nu->bezt;
10529 
10530                                                 for(a=0; a<nu->pntsu; a++, bezt++) {
10531                                                         VECCOPY(bezt->vec[0], data); data+=3;
10532                                                         VECCOPY(bezt->vec[1], data); data+=3;
10533                                                         VECCOPY(bezt->vec[2], data); data+=3;
10534                                                         bezt->alfa= *data; data++;
10535                                                 }
10536                                         }
10537                                         else if(nu->bp) {
10538                                                 BPoint *bp = nu->bp;
10539 
10540                                                 for(a=0; a<nu->pntsu*nu->pntsv; a++, bp++) {
10541                                                         VECCOPY(bp->vec, data); data+=3;
10542                                                         bp->alfa= *data; data++;
10543                                                 }
10544                                         }
10545                                 }
10546                         }
10547                 }
10548         }
10549 
10550         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 8))
10551         {
10552                 {
10553                         Scene *sce= main->scene.first;
10554                         while(sce) {
10555                                 if(sce->r.frame_step==0)
10556                                         sce->r.frame_step= 1;
10557                                 if (sce->r.mblur_samples==0)
10558                                         sce->r.mblur_samples = sce->r.osa;
10559                                 
10560                                 if (sce->ed && sce->ed->seqbase.first) {
10561                                         do_versions_seq_unique_name_all_strips(
10562                                                 sce, &sce->ed->seqbase);
10563                                 }
10564                         
10565                                 sce= sce->id.next;
10566                         }
10567                 }
10568                 {
10569                         /* ensure all nodes have unique names */
10570                         bNodeTree *ntree= main->nodetree.first;
10571                         while(ntree) {
10572                                 bNode *node=ntree->nodes.first;
10573                                 
10574                                 while(node) {
10575                                         nodeUniqueName(ntree, node);
10576                                         node= node->next;
10577                                 }
10578                                 
10579                                 ntree= ntree->id.next;
10580                         }
10581                 }
10582                 {
10583                         Object *ob=main->object.first;
10584                         while (ob) {
10585                                 /* shaded mode disabled for now */
10586                                 if (ob->dt == OB_SHADED) ob->dt = OB_TEXTURE;
10587                                 ob=ob->id.next;
10588                         }
10589                 }
10590                 
10591                 {
10592                         bScreen *screen;
10593                         ScrArea *sa;
10594                         SpaceLink *sl;
10595                         
10596                         for(screen= main->screen.first; screen; screen= screen->id.next) {
10597                                 for(sa= screen->areabase.first; sa; sa= sa->next) {
10598                                         for(sl= sa->spacedata.first; sl; sl= sl->next) {
10599                                                 if(sl->spacetype==SPACE_VIEW3D) {
10600                                                         View3D *v3d = (View3D *)sl;
10601                                                         if (v3d->drawtype == OB_SHADED) v3d->drawtype = OB_SOLID;
10602                                                 }
10603                                         }
10604                                 }
10605                         }
10606                 }
10607                 
10608                 /* only convert old 2.50 files with color management */
10609                 if (main->versionfile == 250) {
10610                         Scene *sce=main->scene.first;
10611                         Material *ma=main->mat.first;
10612                         World *wo=main->world.first;
10613                         Tex *tex=main->tex.first;
10614                         int i, convert=0;
10615                         
10616                         /* convert to new color management system:
10617                          while previously colors were stored as srgb, 
10618                          now they are stored as linear internally, 
10619                          with screen gamma correction in certain places in the UI. */
10620 
10621                         /* don't know what scene is active, so we'll convert if any scene has it enabled... */
10622                         while (sce) {
10623                                 if(sce->r.color_mgt_flag & R_COLOR_MANAGEMENT)
10624                                         convert=1;
10625                                 sce=sce->id.next;
10626                         }
10627                         
10628                         if (convert) {
10629                                 while(ma) {
10630                                         if (ma->ramp_col) {
10631                                                 ColorBand *band = (ColorBand *)ma->ramp_col;
10632                                                 for (i=0; i<band->tot; i++) {
10633                                                         CBData *data = band->data + i;
10634                                                         srgb_to_linearrgb_v3_v3(&data->r, &data->r);
10635                                                 }
10636                                         }
10637                                         if (ma->ramp_spec) {
10638                                                 ColorBand *band = (ColorBand *)ma->ramp_spec;
10639                                                 for (i=0; i<band->tot; i++) {
10640                                                         CBData *data = band->data + i;
10641                                                         srgb_to_linearrgb_v3_v3(&data->r, &data->r);
10642                                                 }
10643                                         }
10644                                         
10645                                         srgb_to_linearrgb_v3_v3(&ma->r, &ma->r);
10646                                         srgb_to_linearrgb_v3_v3(&ma->specr, &ma->specr);
10647                                         srgb_to_linearrgb_v3_v3(&ma->mirr, &ma->mirr);
10648                                         srgb_to_linearrgb_v3_v3(ma->sss_col, ma->sss_col);
10649                                         ma=ma->id.next;
10650                                 }
10651                                 
10652                                 while(tex) {
10653                                         if (tex->coba) {
10654                                                 ColorBand *band = (ColorBand *)tex->coba;
10655                                                 for (i=0; i<band->tot; i++) {
10656                                                         CBData *data = band->data + i;
10657                                                         srgb_to_linearrgb_v3_v3(&data->r, &data->r);
10658                                                 }
10659                                         }
10660                                         tex=tex->id.next;
10661                                 }
10662                                 
10663                                 while(wo) {
10664                                         srgb_to_linearrgb_v3_v3(&wo->ambr, &wo->ambr);
10665                                         srgb_to_linearrgb_v3_v3(&wo->horr, &wo->horr);
10666                                         srgb_to_linearrgb_v3_v3(&wo->zenr, &wo->zenr);
10667                                         wo=wo->id.next;
10668                                 }
10669                         }
10670                 }
10671         }
10672         
10673         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 9))
10674         {
10675                 Scene *sce;
10676                 Mesh *me;
10677                 Object *ob;
10678 
10679                 for(sce=main->scene.first; sce; sce=sce->id.next)
10680                         if(!sce->toolsettings->particle.selectmode)
10681                                 sce->toolsettings->particle.selectmode= SCE_SELECT_PATH;
10682 
10683                 if (main->versionfile == 250 && main->subversionfile > 1) {
10684                         for(me=main->mesh.first; me; me=me->id.next)
10685                                 multires_load_old_250(me);
10686 
10687                         for(ob=main->object.first; ob; ob=ob->id.next) {
10688                                 MultiresModifierData *mmd = (MultiresModifierData *)modifiers_findByType(ob, eModifierType_Multires);
10689 
10690                                 if(mmd) {
10691                                         mmd->totlvl--;
10692                                         mmd->lvl--;
10693                                         mmd->sculptlvl= mmd->lvl;
10694                                         mmd->renderlvl= mmd->lvl;
10695                                 }
10696                         }
10697                 }
10698         }
10699 
10700         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 10))
10701         {
10702                 Object *ob;
10703 
10704                 /* properly initialise hair clothsim data on old files */
10705                 for(ob = main->object.first; ob; ob = ob->id.next) {
10706                         ModifierData *md;
10707                         for(md= ob->modifiers.first; md; md= md->next) {
10708                                 if (md->type == eModifierType_Cloth) {
10709                                         ClothModifierData *clmd = (ClothModifierData *)md;
10710                                         if (clmd->sim_parms->velocity_smooth < 0.01f)
10711                                                 clmd->sim_parms->velocity_smooth = 0.f;
10712                                 }
10713                         }
10714                 }
10715         }
10716 
10717         /* fix bad area setup in subversion 10 */
10718         if (main->versionfile == 250 && main->subversionfile == 10)
10719         {
10720                 /* fix for new view type in sequencer */
10721                 bScreen *screen;
10722                 ScrArea *sa;
10723                 SpaceLink *sl;
10724 
10725 
10726                 /* remove all preview window in wrong spaces */
10727                 for(screen= main->screen.first; screen; screen= screen->id.next) {
10728                         for(sa= screen->areabase.first; sa; sa= sa->next) {
10729                                 for(sl= sa->spacedata.first; sl; sl= sl->next) {
10730                                         if(sl->spacetype!=SPACE_SEQ) {
10731                                                 ARegion *ar;
10732                                                 ListBase *regionbase;
10733 
10734                                                 if (sl == sa->spacedata.first) {
10735                                                         regionbase = &sa->regionbase;
10736                                                 } else {
10737                                                         regionbase = &sl->regionbase;
10738                                                 }
10739 
10740 
10741                                                 for( ar = regionbase->first; ar; ar = ar->next) {
10742                                                         if (ar->regiontype == RGN_TYPE_PREVIEW)
10743                                                                 break;
10744                                                 }
10745 
10746                                                 if (ar && (ar->regiontype == RGN_TYPE_PREVIEW)) {
10747                                                         SpaceType *st= BKE_spacetype_from_id(SPACE_SEQ);
10748                                                         BKE_area_region_free(st, ar);
10749                                                         BLI_freelinkN(regionbase, ar);
10750                                                 }
10751                                         }
10752                                 }
10753                         }
10754                 }
10755         }
10756 
10757         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 11))
10758         {
10759                 {
10760                         /* fix for new view type in sequencer */
10761                         bScreen *screen;
10762                         ScrArea *sa;
10763                         SpaceLink *sl;
10764 
10765 
10766                         for(screen= main->screen.first; screen; screen= screen->id.next) {
10767                                 for(sa= screen->areabase.first; sa; sa= sa->next) {
10768                                         for(sl= sa->spacedata.first; sl; sl= sl->next) {
10769                                                 if(sl->spacetype==SPACE_SEQ) {
10770                                                         ARegion *ar;
10771                                                         ARegion *ar_main;
10772                                                         ListBase *regionbase;
10773                                                         SpaceSeq *sseq = (SpaceSeq *)sl;
10774 
10775                                                         if (sl == sa->spacedata.first) {
10776                                                                 regionbase = &sa->regionbase;
10777                                                         } else {
10778                                                                 regionbase = &sl->regionbase;
10779                                                         }
10780 
10781                                                         if (sseq->view == 0) sseq->view = SEQ_VIEW_SEQUENCE;
10782                                                         if (sseq->mainb == 0) sseq->mainb = SEQ_DRAW_IMG_IMBUF;
10783 
10784                                                         ar_main = (ARegion*)regionbase->first;
10785                                                         for (; ar_main; ar_main = ar_main->next) {
10786                                                                 if (ar_main->regiontype == RGN_TYPE_WINDOW)
10787                                                                         break;
10788                                                         }
10789                                                         ar= MEM_callocN(sizeof(ARegion), "preview area for sequencer");
10790                                                         BLI_insertlinkbefore(regionbase, ar_main, ar);
10791                                                         sequencer_init_preview_region(ar);
10792                                                 }
10793                                         }
10794                                 }
10795                         }
10796                 }
10797         }
10798 
10799         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 12))
10800         {
10801                 Scene *sce;
10802                 Object *ob;
10803                 Brush *brush;
10804                 Material *ma;
10805                 
10806                 /* game engine changes */
10807                 for(sce = main->scene.first; sce; sce = sce->id.next) {
10808                         sce->gm.eyeseparation = 0.10f;
10809                 }
10810                 
10811                 /* anim viz changes */
10812                 for (ob= main->object.first; ob; ob= ob->id.next) {
10813                         /* initialise object defaults */
10814                         animviz_settings_init(&ob->avs);
10815                         
10816                         /* if armature, copy settings for pose from armature data 
10817                          * performing initialisation where appropriate 
10818                          */
10819                         if (ob->pose && ob->data) {
10820                                 bArmature *arm= newlibadr(fd, lib, ob->data);
10821                                 if(arm) { /* XXX - why does this fail in some cases? */
10822                                         bAnimVizSettings *avs= &ob->pose->avs;
10823                                         
10824                                         /* ghosting settings ---------------- */
10825                                                 /* ranges */
10826                                         avs->ghost_bc= avs->ghost_ac= arm->ghostep;
10827                                         
10828                                         avs->ghost_sf= arm->ghostsf;
10829                                         avs->ghost_ef= arm->ghostef;
10830                                         if ((avs->ghost_sf == avs->ghost_ef) && (avs->ghost_sf == 0)) {
10831                                                 avs->ghost_sf= 1;
10832                                                 avs->ghost_ef= 100;
10833                                         }
10834                                         
10835                                                 /* type */
10836                                         if (arm->ghostep == 0)
10837                                                 avs->ghost_type= GHOST_TYPE_NONE;
10838                                         else
10839                                                 avs->ghost_type= arm->ghosttype + 1;
10840                                         
10841                                                 /* stepsize */
10842                                         avs->ghost_step= arm->ghostsize;
10843                                         if (avs->ghost_step == 0)
10844                                                 avs->ghost_step= 1;
10845                                         
10846                                         /* path settings --------------------- */
10847                                                 /* ranges */
10848                                         avs->path_bc= arm->pathbc;
10849                                         avs->path_ac= arm->pathac;
10850                                         if ((avs->path_bc == avs->path_ac) && (avs->path_bc == 0))
10851                                                 avs->path_bc= avs->path_ac= 10;
10852                                         
10853                                         avs->path_sf= arm->pathsf;
10854                                         avs->path_ef= arm->pathef;
10855                                         if ((avs->path_sf == avs->path_ef) && (avs->path_sf == 0)) {
10856                                                 avs->path_sf= 1;
10857                                                 avs->path_ef= 250;
10858                                         }
10859                                         
10860                                                 /* flags */
10861                                         if (arm->pathflag & ARM_PATH_FNUMS)
10862                                                 avs->path_viewflag |= MOTIONPATH_VIEW_FNUMS;
10863                                         if (arm->pathflag & ARM_PATH_KFRAS)
10864                                                 avs->path_viewflag |= MOTIONPATH_VIEW_KFRAS;
10865                                         if (arm->pathflag & ARM_PATH_KFNOS)
10866                                                 avs->path_viewflag |= MOTIONPATH_VIEW_KFNOS;
10867                                         
10868                                                 /* bake flags */
10869                                         if (arm->pathflag & ARM_PATH_HEADS)
10870                                                 avs->path_bakeflag |= MOTIONPATH_BAKE_HEADS;
10871                                         
10872                                                 /* type */
10873                                         if (arm->pathflag & ARM_PATH_ACFRA)
10874                                                 avs->path_type = MOTIONPATH_TYPE_ACFRA;
10875                                         
10876                                                 /* stepsize */
10877                                         avs->path_step= arm->pathsize;
10878                                         if (avs->path_step == 0)
10879                                                 avs->path_step= 1;
10880                                 }
10881                                 else
10882                                         animviz_settings_init(&ob->pose->avs);
10883                         }
10884                 }
10885                 
10886                 /* brush texture changes */
10887                 for (brush= main->brush.first; brush; brush= brush->id.next) {
10888                         default_mtex(&brush->mtex);
10889                 }
10890 
10891                 for (ma= main->mat.first; ma; ma= ma->id.next) {
10892                         if (ma->vol.ms_spread < 0.0001f) {
10893                                 ma->vol.ms_spread = 0.2f;
10894                                 ma->vol.ms_diff = 1.f;
10895                                 ma->vol.ms_intensity = 1.f;     
10896                         }
10897                 }
10898         }
10899         
10900         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 13)) {
10901                 /* NOTE: if you do more conversion, be sure to do it outside of this and
10902                    increase subversion again, otherwise it will not be correct */
10903                 Object *ob;
10904                 
10905                 /* convert degrees to radians for internal use */
10906                 for (ob=main->object.first; ob; ob=ob->id.next) {
10907                         bPoseChannel *pchan;
10908 
10909                         do_version_constraints_radians_degrees_250(&ob->constraints);
10910 
10911                         if (ob->pose) {
10912                                 for (pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
10913                                         pchan->limitmin[0] *= (float)(M_PI/180.0);
10914                                         pchan->limitmin[1] *= (float)(M_PI/180.0);
10915                                         pchan->limitmin[2] *= (float)(M_PI/180.0);
10916                                         pchan->limitmax[0] *= (float)(M_PI/180.0);
10917                                         pchan->limitmax[1] *= (float)(M_PI/180.0);
10918                                         pchan->limitmax[2] *= (float)(M_PI/180.0);
10919 
10920                                         do_version_constraints_radians_degrees_250(&pchan->constraints);
10921                                 }
10922                         }
10923                 }
10924         }
10925         
10926         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 14)) {
10927                 /* fix for bad View2D extents for Animation Editors */
10928                 bScreen *screen;
10929                 ScrArea *sa;
10930                 SpaceLink *sl;
10931                 
10932                 for (screen= main->screen.first; screen; screen= screen->id.next) {
10933                         for (sa= screen->areabase.first; sa; sa= sa->next) {
10934                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
10935                                         ListBase *regionbase;
10936                                         ARegion *ar;
10937                                         
10938                                         if (sl == sa->spacedata.first)
10939                                                 regionbase = &sa->regionbase;
10940                                         else
10941                                                 regionbase = &sl->regionbase;
10942                                                 
10943                                         if (ELEM(sl->spacetype, SPACE_ACTION, SPACE_NLA)) {
10944                                                 for (ar = (ARegion*)regionbase->first; ar; ar = ar->next) {
10945                                                         if (ar->regiontype == RGN_TYPE_WINDOW) {
10946                                                                 ar->v2d.cur.ymax= ar->v2d.tot.ymax= 0.0f;
10947                                                                 ar->v2d.cur.ymin= ar->v2d.tot.ymin= (float)(-sa->winy) / 3.0f;
10948                                                         }
10949                                                 }
10950                                         }
10951                                 }
10952                         }
10953                 }
10954         }
10955         
10956         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 15)) {
10957                 World *wo;
10958                 Material *ma;
10959 
10960                 /* ambient default from 0.5f to 1.0f */
10961                 for(ma= main->mat.first; ma; ma=ma->id.next)
10962                         ma->amb *= 2.0f;
10963 
10964                 for(wo= main->world.first; wo; wo=wo->id.next) {
10965                         /* ao splitting into ao/env/indirect */
10966                         wo->ao_env_energy= wo->aoenergy;
10967                         wo->aoenergy= 1.0f;
10968 
10969                         if(wo->ao_indirect_bounces == 0)
10970                                 wo->ao_indirect_bounces= 1;
10971                         else
10972                                 wo->mode |= WO_INDIRECT_LIGHT;
10973 
10974                         if(wo->aomix == WO_AOSUB)
10975                                 wo->ao_env_energy= -wo->ao_env_energy;
10976                         else if(wo->aomix == WO_AOADDSUB)
10977                                 wo->mode |= WO_AMB_OCC;
10978 
10979                         wo->aomix= WO_AOMUL;
10980 
10981                         /* ambient default from 0.5f to 1.0f */
10982                         mul_v3_fl(&wo->ambr, 0.5f);
10983                         wo->ao_env_energy *= 0.5f;
10984                 }
10985         }
10986         
10987         if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 17)) {
10988                 Scene *sce;
10989                 Sequence *seq;
10990                 Material *ma;
10991 
10992                 /* initialize to sane default so toggling on border shows something */
10993                 for(sce = main->scene.first; sce; sce = sce->id.next) {
10994                         if(sce->r.border.xmin == 0.0f && sce->r.border.ymin == 0.0f &&
10995                            sce->r.border.xmax == 0.0f && sce->r.border.ymax == 0.0f) {
10996                                 sce->r.border.xmin= 0.0f;
10997                                 sce->r.border.ymin= 0.0f;
10998                                 sce->r.border.xmax= 1.0f;
10999                                 sce->r.border.ymax= 1.0f;
11000                         }
11001 
11002                         if((sce->r.ffcodecdata.flags & FFMPEG_MULTIPLEX_AUDIO) == 0)
11003                                 sce->r.ffcodecdata.audio_codec = 0x0; // CODEC_ID_NONE
11004 
11005                         SEQ_BEGIN(sce->ed, seq) {
11006                                 seq->volume = 1.0f;
11007                         }
11008                         SEQ_END
11009                 }
11010 
11011                 /* particle brush strength factor was changed from int to float */
11012                 for(sce= main->scene.first; sce; sce=sce->id.next) {
11013                         ParticleEditSettings *pset= &sce->toolsettings->particle;
11014                         int a;
11015 
11016                         for(a=0; a<PE_TOT_BRUSH; a++)
11017                                 pset->brush[a].strength /= 100.0f;
11018                 }
11019 
11020                 for(ma = main->mat.first; ma; ma=ma->id.next)
11021                         if(ma->mode & MA_TRACEBLE)
11022                                 ma->shade_flag |= MA_APPROX_OCCLUSION;
11023 
11024                 /* sequencer changes */
11025                 {
11026                         bScreen *screen;
11027                         ScrArea *sa;
11028                         SpaceLink *sl;
11029 
11030                         for(screen= main->screen.first; screen; screen= screen->id.next) {
11031                                 for(sa= screen->areabase.first; sa; sa= sa->next) {
11032                                         for(sl= sa->spacedata.first; sl; sl= sl->next) {
11033                                                 if(sl->spacetype==SPACE_SEQ) {
11034                                                         ARegion *ar_preview;
11035                                                         ListBase *regionbase;
11036 
11037                                                         if (sl == sa->spacedata.first) {
11038                                                                 regionbase = &sa->regionbase;
11039                                                         } else {
11040                                                                 regionbase = &sl->regionbase;
11041                                                         }
11042 
11043                                                         ar_preview = (ARegion*)regionbase->first;
11044                                                         for (; ar_preview; ar_preview = ar_preview->next) {
11045                                                                 if (ar_preview->regiontype == RGN_TYPE_PREVIEW)
11046                                                                         break;
11047                                                         }
11048                                                         if (ar_preview && (ar_preview->regiontype == RGN_TYPE_PREVIEW)) {
11049                                                                 sequencer_init_preview_region(ar_preview);
11050                                                         }
11051                                                 }
11052                                         }
11053                                 }
11054                         }
11055                 } /* sequencer changes */
11056         }
11057         
11058         if (main->versionfile <= 251) { /* 2.5.1 had no subversions */
11059                 bScreen *sc;
11060                 
11061                 /* Blender 2.5.2 - subversion 0 introduced a new setting: V3D_RENDER_OVERRIDE.
11062                  * This bit was used in the past for V3D_TRANSFORM_SNAP, which is now deprecated. 
11063                  * Here we clear it for old files so they don't come in with V3D_RENDER_OVERRIDE set,
11064                  * which would cause cameras, lamps, etc to become invisible */
11065                 for(sc= main->screen.first; sc; sc= sc->id.next) {
11066                         ScrArea *sa;
11067                         for(sa= sc->areabase.first; sa; sa= sa->next) {
11068                                 SpaceLink *sl;
11069                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11070                                         if(sl->spacetype==SPACE_VIEW3D) {
11071                                                 View3D* v3d = (View3D *)sl;
11072                                                 v3d->flag2 &= ~V3D_RENDER_OVERRIDE;
11073                                         }
11074                                 }
11075                         }
11076                 }
11077         }
11078 
11079         if (main->versionfile < 252 || (main->versionfile == 252 && main->subversionfile < 1)) {
11080                 Brush *brush;
11081                 Object *ob;
11082                 Scene *scene;
11083                 bNodeTree *ntree;
11084                 
11085                 for (brush= main->brush.first; brush; brush= brush->id.next) {
11086                         if (brush->curve) brush->curve->preset = CURVE_PRESET_SMOOTH;
11087                 }
11088                 
11089                 /* properly initialise active flag for fluidsim modifiers */
11090                 for(ob = main->object.first; ob; ob = ob->id.next) {
11091                         ModifierData *md;
11092                         for(md= ob->modifiers.first; md; md= md->next) {
11093                                 if (md->type == eModifierType_Fluidsim) {
11094                                         FluidsimModifierData *fmd = (FluidsimModifierData *)md;
11095                                         fmd->fss->flag |= OB_FLUIDSIM_ACTIVE; 
11096                                         fmd->fss->flag |= OB_FLUIDSIM_OVERRIDE_TIME;
11097                                 }
11098                         }
11099                 }
11100                 
11101                 /* adjustment to color balance node values */
11102                 for(scene= main->scene.first; scene; scene= scene->id.next) {
11103                         if(scene->nodetree) {
11104                                 bNode *node=scene->nodetree->nodes.first;
11105                                 
11106                                 while(node) {
11107                                         if (node->type == CMP_NODE_COLORBALANCE) {
11108                                                 NodeColorBalance *n= (NodeColorBalance *)node->storage;
11109                                                 n->lift[0] += 1.f;
11110                                                 n->lift[1] += 1.f;
11111                                                 n->lift[2] += 1.f;
11112                                         }
11113                                         node= node->next;
11114                                 }
11115                         }
11116                 }
11117                 /* check inside node groups too */
11118                 for (ntree= main->nodetree.first; ntree; ntree=ntree->id.next) {
11119                         bNode *node=ntree->nodes.first;
11120                         
11121                         while(node) {
11122                                 if (node->type == CMP_NODE_COLORBALANCE) {
11123                                         NodeColorBalance *n= (NodeColorBalance *)node->storage;
11124                                         n->lift[0] += 1.f;
11125                                         n->lift[1] += 1.f;
11126                                         n->lift[2] += 1.f;
11127                                 }
11128                                 node= node->next;
11129                         }
11130                 }
11131         }
11132         
11133         /* old-track -> constraints (this time we're really doing it!) */
11134         if (main->versionfile < 252 || (main->versionfile == 252 && main->subversionfile < 2)) {
11135                 Object *ob;
11136                 
11137                 for (ob = main->object.first; ob; ob = ob->id.next)
11138                         do_version_old_trackto_to_constraints(ob);
11139         }
11140         
11141         if (main->versionfile < 252 || (main->versionfile == 252 && main->subversionfile < 5)) {
11142                 bScreen *sc;
11143                 
11144                 /* Image editor scopes */
11145                 for(sc= main->screen.first; sc; sc= sc->id.next) {
11146                         ScrArea *sa;
11147                         for(sa= sc->areabase.first; sa; sa= sa->next) {
11148                                 SpaceLink *sl;
11149                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11150                                         if(sl->spacetype==SPACE_IMAGE) {
11151                                                 SpaceImage *sima = (SpaceImage *)sl;
11152                                                 scopes_new(&sima->scopes);
11153                                         }
11154                                 }
11155                         }
11156                 }
11157         }
11158         
11159 
11160         if (main->versionfile < 253)
11161         {
11162                 Object *ob;
11163                 Scene *scene;
11164                 bScreen *sc;
11165                 Tex *tex;
11166                 Brush *brush;
11167 
11168                 for (sc= main->screen.first; sc; sc= sc->id.next) {
11169                         ScrArea *sa;
11170                         for (sa= sc->areabase.first; sa; sa= sa->next) {
11171                                 SpaceLink *sl;
11172                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11173                                         if (sl->spacetype == SPACE_NODE) {
11174                                                 SpaceNode *snode= (SpaceNode *)sl;
11175                                                 ListBase *regionbase;
11176                                                 ARegion *ar;
11177 
11178                                                 if (sl == sa->spacedata.first)
11179                                                         regionbase = &sa->regionbase;
11180                                                 else
11181                                                         regionbase = &sl->regionbase;
11182 
11183                                                 if (snode->v2d.minzoom > 0.09f)
11184                                                         snode->v2d.minzoom= 0.09f;
11185                                                 if (snode->v2d.maxzoom < 2.31f)
11186                                                         snode->v2d.maxzoom= 2.31f;
11187 
11188                                                 for (ar= regionbase->first; ar; ar= ar->next) {
11189                                                         if (ar->regiontype == RGN_TYPE_WINDOW) {
11190                                                                 if (ar->v2d.minzoom > 0.09f)
11191                                                                         ar->v2d.minzoom= 0.09f;
11192                                                                 if (ar->v2d.maxzoom < 2.31f)
11193                                                                         ar->v2d.maxzoom= 2.31f;
11194                                                         }
11195                                                 }
11196                                         }
11197                                         else if (sl->spacetype == SPACE_TIME) {
11198                                                 SpaceTime *stime= (SpaceTime *)sl;
11199                                                 
11200                                                 /* enable all cache display */
11201                                                 stime->cache_display |= TIME_CACHE_DISPLAY;
11202                                                 stime->cache_display |= (TIME_CACHE_SOFTBODY|TIME_CACHE_PARTICLES);
11203                                                 stime->cache_display |= (TIME_CACHE_CLOTH|TIME_CACHE_SMOKE);
11204                                         }
11205                                 }
11206                         }
11207                 }
11208 
11209                 do_version_mdef_250(main);
11210 
11211                 /* parent type to modifier */
11212                 for(ob = main->object.first; ob; ob = ob->id.next) {
11213                         if(ob->parent) {
11214                                 Object *parent= (Object *)newlibadr(fd, lib, ob->parent);
11215                                 if(parent) { /* parent may not be in group */
11216                                         if(parent->type==OB_ARMATURE && ob->partype==PARSKEL) {
11217                                                 ArmatureModifierData *amd;
11218                                                 bArmature *arm= (bArmature *)newlibadr(fd, lib, parent->data);
11219 
11220                                                 amd = (ArmatureModifierData*) modifier_new(eModifierType_Armature);
11221                                                 amd->object = ob->parent;
11222                                                 BLI_addtail((ListBase*)&ob->modifiers, amd);
11223                                                 amd->deformflag= arm->deformflag;
11224                                                 ob->partype = PAROBJECT;
11225                                         }
11226                                         else if(parent->type==OB_LATTICE && ob->partype==PARSKEL) {
11227                                                 LatticeModifierData *lmd;
11228 
11229                                                 lmd = (LatticeModifierData*) modifier_new(eModifierType_Lattice);
11230                                                 lmd->object = ob->parent;
11231                                                 BLI_addtail((ListBase*)&ob->modifiers, lmd);
11232                                                 ob->partype = PAROBJECT;
11233                                         }
11234                                         else if(parent->type==OB_CURVE && ob->partype==PARCURVE) {
11235                                                 CurveModifierData *cmd;
11236 
11237                                                 cmd = (CurveModifierData*) modifier_new(eModifierType_Curve);
11238                                                 cmd->object = ob->parent;
11239                                                 BLI_addtail((ListBase*)&ob->modifiers, cmd);
11240                                                 ob->partype = PAROBJECT;
11241                                         }
11242                                 }
11243                         }
11244                 }
11245                 
11246                 /* initialise scene active layer */
11247                 for (scene= main->scene.first; scene; scene=scene->id.next) {
11248                         int i;
11249                         for(i=0; i<20; i++) {
11250                                 if(scene->lay & (1<<i)) {
11251                                         scene->layact= 1<<i;
11252                                         break;
11253                                 }
11254                         }
11255                 }
11256 
11257                 for(tex= main->tex.first; tex; tex= tex->id.next) {
11258                         /* if youre picky, this isn't correct until we do a version bump
11259                          * since you could set saturation to be 0.0*/
11260                         if(tex->saturation==0.0f)
11261                                 tex->saturation= 1.0f;
11262                 }
11263 
11264                 {
11265                         Curve *cu;
11266                         for(cu= main->curve.first; cu; cu= cu->id.next) {
11267                                 cu->smallcaps_scale= 0.75f;
11268                         }
11269                 }
11270 
11271                 for (scene= main->scene.first; scene; scene=scene->id.next) {
11272                         if(scene) {
11273                                 Sequence *seq;
11274                                 SEQ_BEGIN(scene->ed, seq) {
11275                                         if(seq->sat==0.0f) {
11276                                                 seq->sat= 1.0f;
11277                                         }
11278                                 }
11279                                 SEQ_END
11280                         }
11281                 }
11282 
11283                 /* GSOC 2010 Sculpt - New settings for Brush */
11284 
11285                 for (brush= main->brush.first; brush; brush= brush->id.next) {
11286                         /* Sanity Check */
11287 
11288                         // infinite number of dabs
11289                         if (brush->spacing == 0)
11290                                 brush->spacing = 10;
11291 
11292                         // will have no effect
11293                         if (brush->alpha == 0)
11294                                 brush->alpha = 0.5f;
11295 
11296                         // bad radius
11297                         if (brush->unprojected_radius == 0)
11298                                 brush->unprojected_radius = 0.125f;
11299 
11300                         // unusable size
11301                         if (brush->size == 0)
11302                                 brush->size = 35;
11303 
11304                         // can't see overlay
11305                         if (brush->texture_overlay_alpha == 0)
11306                                 brush->texture_overlay_alpha = 33;
11307 
11308                         // same as draw brush
11309                         if (brush->crease_pinch_factor == 0)
11310                                 brush->crease_pinch_factor = 0.5f;
11311 
11312                         // will sculpt no vertexes
11313                         if (brush->plane_trim == 0)
11314                                 brush->plane_trim = 0.5f;
11315 
11316                         // same as smooth stroke off
11317                         if (brush->smooth_stroke_radius == 0)
11318                                 brush->smooth_stroke_radius= 75;
11319 
11320                         // will keep cursor in one spot
11321                         if (brush->smooth_stroke_radius == 1)
11322                                 brush->smooth_stroke_factor= 0.9f;
11323 
11324                         // same as dots
11325                         if (brush->rate == 0)
11326                                 brush->rate = 0.1f;
11327 
11328                         /* New Settings */
11329                         if (main->versionfile < 252 || (main->versionfile == 252 && main->subversionfile < 5)) {
11330                                 brush->flag |= BRUSH_SPACE_ATTEN; // explicitly enable adaptive space
11331 
11332                                 // spacing was originally in pixels, convert it to percentage for new version
11333                                 // size should not be zero due to sanity check above
11334                                 brush->spacing = (int)(100*((float)brush->spacing) / ((float)brush->size));
11335 
11336                                 if (brush->add_col[0] == 0 &&
11337                                         brush->add_col[1] == 0 &&
11338                                         brush->add_col[2] == 0)
11339                                 {
11340                                         brush->add_col[0] = 1.00f;
11341                                         brush->add_col[1] = 0.39f;
11342                                         brush->add_col[2] = 0.39f;
11343                                 }
11344 
11345                                 if (brush->sub_col[0] == 0 &&
11346                                         brush->sub_col[1] == 0 &&
11347                                         brush->sub_col[2] == 0)
11348                                 {
11349                                         brush->sub_col[0] = 0.39f;
11350                                         brush->sub_col[1] = 0.39f;
11351                                         brush->sub_col[2] = 1.00f;
11352                                 }
11353                         }
11354                 }
11355         }
11356 
11357         /* GSOC Sculpt 2010 - Sanity check on Sculpt/Paint settings */
11358         if (main->versionfile < 253) {
11359                 Scene *sce;
11360                 for (sce= main->scene.first; sce; sce= sce->id.next) {
11361                         if (sce->toolsettings->sculpt_paint_unified_alpha == 0)
11362                                 sce->toolsettings->sculpt_paint_unified_alpha = 0.5f;
11363 
11364                         if (sce->toolsettings->sculpt_paint_unified_unprojected_radius == 0) 
11365                                 sce->toolsettings->sculpt_paint_unified_unprojected_radius = 0.125f;
11366 
11367                         if (sce->toolsettings->sculpt_paint_unified_size == 0)
11368                                 sce->toolsettings->sculpt_paint_unified_size = 35;
11369                 }
11370         }
11371 
11372         if (main->versionfile < 253 || (main->versionfile == 253 && main->subversionfile < 1))
11373                 {
11374                         Object *ob;
11375 
11376                         for(ob = main->object.first; ob; ob = ob->id.next) {
11377                                 ModifierData *md;
11378                                 for(md= ob->modifiers.first; md; md= md->next) {
11379                                         if (md->type == eModifierType_Smoke) {
11380                                                 SmokeModifierData *smd = (SmokeModifierData *)md;
11381 
11382                                                 if((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain)
11383                                                 {
11384                                                         smd->domain->vorticity = 2.0f;
11385                                                         smd->domain->time_scale = 1.0f;
11386 
11387                                                         if(!(smd->domain->flags & (1<<4)))
11388                                                                 continue;
11389 
11390                                                         /* delete old MOD_SMOKE_INITVELOCITY flag */
11391                                                         smd->domain->flags &= ~(1<<4);
11392 
11393                                                         /* for now just add it to all flow objects in the scene */
11394                                                         {
11395                                                                 Object *ob2;
11396                                                                 for(ob2 = main->object.first; ob2; ob2 = ob2->id.next) {
11397                                                                         ModifierData *md2;
11398                                                                         for(md2= ob2->modifiers.first; md2; md2= md2->next) {
11399                                                                                 if (md2->type == eModifierType_Smoke) {
11400                                                                                         SmokeModifierData *smd2 = (SmokeModifierData *)md2;
11401 
11402                                                                                         if((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
11403                                                                                         {
11404                                                                                                 smd2->flow->flags |= MOD_SMOKE_FLOW_INITVELOCITY;
11405                                                                                         }
11406                                                                                 }
11407                                                                         }
11408                                                                 }
11409                                                         }
11410 
11411                                                 }
11412                                                 else if((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow)
11413                                                 {
11414                                                         smd->flow->vel_multi = 1.0f;
11415                                                 }
11416 
11417                                         }
11418                                 }
11419                         }
11420                 }
11421 
11422         if (main->versionfile < 255 || (main->versionfile == 255 && main->subversionfile < 1)) {
11423                 Brush *br;
11424                 ParticleSettings *part;
11425                 bScreen *sc;
11426                 Object *ob;
11427 
11428                 for(br= main->brush.first; br; br= br->id.next) {
11429                         if(br->ob_mode==0)
11430                                 br->ob_mode= OB_MODE_ALL_PAINT;
11431                 }
11432 
11433                 for(part = main->particle.first; part; part = part->id.next) {
11434                         if(part->boids)
11435                                 part->boids->pitch = 1.0f;
11436 
11437                         part->flag &= ~PART_HAIR_REGROW; /* this was a deprecated flag before */
11438                         part->kink_amp_clump = 1.f; /* keep old files looking similar */
11439                 }
11440 
11441                 for (sc= main->screen.first; sc; sc= sc->id.next) {
11442                         ScrArea *sa;
11443                         for (sa= sc->areabase.first; sa; sa= sa->next) {
11444                                 SpaceLink *sl;
11445                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11446                                         if (sl->spacetype == SPACE_INFO) {
11447                                                 SpaceInfo *sinfo= (SpaceInfo *)sl;
11448                                                 ARegion *ar;
11449 
11450                                                 sinfo->rpt_mask= INFO_RPT_OP;
11451 
11452                                                 for (ar= sa->regionbase.first; ar; ar= ar->next) {
11453                                                         if (ar->regiontype == RGN_TYPE_WINDOW) {
11454                                                                 ar->v2d.scroll = (V2D_SCROLL_RIGHT);
11455                                                                 ar->v2d.align = V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_NEG_Y; /* align bottom left */
11456                                                                 ar->v2d.keepofs = V2D_LOCKOFS_X;
11457                                                                 ar->v2d.keepzoom = (V2D_LOCKZOOM_X|V2D_LOCKZOOM_Y|V2D_LIMITZOOM|V2D_KEEPASPECT);
11458                                                                 ar->v2d.keeptot= V2D_KEEPTOT_BOUNDS;
11459                                                                 ar->v2d.minzoom= ar->v2d.maxzoom= 1.0f;
11460                                                         }
11461                                                 }
11462                                         }
11463                                 }
11464                         }
11465                 }
11466 
11467                 /* fix rotation actuators for objects so they use real angles (radians)
11468                  * since before blender went opensource this strange scalar was used: (1 / 0.02) * 2 * math.pi/360 */
11469                 for(ob= main->object.first; ob; ob= ob->id.next) {
11470                         bActuator *act= ob->actuators.first;
11471                         while(act) {
11472                                 if (act->type==ACT_OBJECT) {
11473                                         /* multiply velocity with 50 in old files */
11474                                         bObjectActuator *oa= act->data;
11475                                         mul_v3_fl(oa->drot, 0.8726646259971648f);
11476                                 }
11477                                 act= act->next;
11478                         }
11479                 }
11480         }
11481         
11482         if (main->versionfile < 256) {
11483                 bScreen *sc;
11484                 ScrArea *sa;
11485                 Key *key;
11486                 
11487                 /* Fix for sample line scope initializing with no height */
11488                 for(sc= main->screen.first; sc; sc= sc->id.next) {
11489                         sa= sc->areabase.first;
11490                         while(sa) {
11491                                 SpaceLink *sl;
11492                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11493                                         if(sl->spacetype==SPACE_IMAGE) {
11494                                                 SpaceImage *sima= (SpaceImage *)sl;
11495                                                 if (sima->sample_line_hist.height == 0 )
11496                                                         sima->sample_line_hist.height = 100;
11497                                         }
11498                                 }
11499                                 sa= sa->next;
11500                         }
11501                 }
11502                 
11503                 /* old files could have been saved with slidermin = slidermax = 0.0, but the UI in
11504                  * 2.4x would never reveal this to users as a dummy value always ended up getting used
11505                  * instead
11506                  */
11507                 for (key = main->key.first; key; key = key->id.next) {
11508                         KeyBlock *kb;
11509                         
11510                         for (kb = key->block.first; kb; kb = kb->next) {
11511                                 if (IS_EQF(kb->slidermin, kb->slidermax) && IS_EQ(kb->slidermax, 0))
11512                                         kb->slidermax = kb->slidermin + 1.0f;
11513                         }
11514                 }
11515         }
11516         
11517         if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile < 1)) {
11518                 /* fix for bones that didn't have arm_roll before */
11519                 bArmature* arm;
11520                 Bone* bone;
11521                 Object *ob;
11522 
11523                 for (arm = main->armature.first; arm; arm = arm->id.next)
11524                         for (bone = arm->bonebase.first; bone; bone = bone->next)
11525                                 do_version_bone_roll_256(bone);
11526 
11527                 /* fix for objects which have zero dquat's
11528                  * since this is multiplied with the quat rather than added */
11529                 for(ob= main->object.first; ob; ob= ob->id.next) {
11530                         if(is_zero_v4(ob->dquat)) {
11531                                 unit_qt(ob->dquat);
11532                         }
11533                         if(is_zero_v3(ob->drotAxis) && ob->drotAngle == 0.0f) {
11534                                 unit_axis_angle(ob->drotAxis, &ob->drotAngle);
11535                         }
11536                 }
11537         }
11538 
11539         if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile < 2)) {
11540                 bNodeTree *ntree;
11541                 
11542                 /* node sockets are not exposed automatically any more,
11543                  * this mimics the old behaviour by adding all unlinked sockets to groups.
11544                  */
11545                 for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next) {
11546                         /* XXX Only setting a flag here. Actual adding of group sockets
11547                          * is done in lib_verify_nodetree, because at this point the internal
11548                          * nodes may not be up-to-date! (missing lib-link)
11549                          */
11550                         ntree->flag |= NTREE_DO_VERSIONS;
11551                 }
11552         }
11553 
11554         if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile <3)){
11555                 bScreen *sc;
11556                 Brush *brush;
11557                 Object *ob;
11558                 ParticleSettings *part;
11559                 Material *mat;
11560                 int tex_nr, transp_tex;
11561                 
11562                 for(mat = main->mat.first; mat; mat = mat->id.next){
11563                         if(!(mat->mode & MA_TRANSP) && !(mat->material_type & MA_TYPE_VOLUME)){
11564                                 
11565                                 transp_tex= 0;
11566                                 
11567                                 for(tex_nr=0; tex_nr<MAX_MTEX; tex_nr++){
11568                                         if(!mat->mtex[tex_nr]) continue;
11569                                         if(mat->mtex[tex_nr]->mapto & MAP_ALPHA) transp_tex= 1;
11570                                 }
11571                                 
11572                                 if(mat->alpha < 1.0f || mat->fresnel_tra > 0.0f || transp_tex){
11573                                         mat->mode |= MA_TRANSP;
11574                                         mat->mode &= ~(MA_ZTRANSP|MA_RAYTRANSP);
11575                                 }
11576                         }
11577                 }
11578 
11579                 /* redraws flag in SpaceTime has been moved to Screen level */
11580                 for (sc = main->screen.first; sc; sc= sc->id.next) {
11581                         if (sc->redraws_flag == 0) {
11582                                 /* just initialise to default? */
11583                                 // XXX: we could also have iterated through areas, and taken them from the first timeline available...
11584                                 sc->redraws_flag = TIME_ALL_3D_WIN|TIME_ALL_ANIM_WIN;
11585                         }
11586                 }
11587 
11588                 for (brush= main->brush.first; brush; brush= brush->id.next) {
11589                         if(brush->height == 0)
11590                                 brush->height= 0.4f;
11591                 }
11592 
11593                 /* replace 'rim material' option for in offset*/
11594                 for(ob = main->object.first; ob; ob = ob->id.next) {
11595                         ModifierData *md;
11596                         for(md= ob->modifiers.first; md; md= md->next) {
11597                                 if (md->type == eModifierType_Solidify) {
11598                                         SolidifyModifierData *smd = (SolidifyModifierData *)md;
11599                                         if(smd->flag & MOD_SOLIDIFY_RIM_MATERIAL) {
11600                                                 smd->mat_ofs_rim= 1;
11601                                                 smd->flag &= ~MOD_SOLIDIFY_RIM_MATERIAL;
11602                                         }
11603                                 }
11604                         }
11605                 }
11606 
11607                 /* particle draw color from material */
11608                 for(part = main->particle.first; part; part = part->id.next) {
11609                         if(part->draw & PART_DRAW_MAT_COL)
11610                                 part->draw_col = PART_DRAW_COL_MAT;
11611                 }
11612         }
11613 
11614         if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile < 6)){
11615                 Mesh *me;
11616 
11617                 for(me= main->mesh.first; me; me= me->id.next)
11618                         mesh_calc_normals(me->mvert, me->totvert, me->mface, me->totface, NULL);
11619         }
11620 
11621         if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile < 2)){
11622                 /* update blur area sizes from 0..1 range to 0..100 percentage */
11623                 Scene *scene;
11624                 bNode *node;
11625                 for (scene=main->scene.first; scene; scene=scene->id.next)
11626                         if (scene->nodetree)
11627                                 for (node=scene->nodetree->nodes.first; node; node=node->next)
11628                                         if (node->type==CMP_NODE_BLUR) {
11629                                                 NodeBlurData *nbd= node->storage;
11630                                                 nbd->percentx *= 100.0f;
11631                                                 nbd->percenty *= 100.0f;
11632                                         }
11633         }
11634 
11635         if (main->versionfile < 258 || (main->versionfile == 258 && main->subversionfile < 1)){
11636                 /* screen view2d settings were not properly initialized [#27164]
11637                  * v2d->scroll caused the bug but best reset other values too which are in old blend files only.
11638                  * need to make less ugly - possibly an iterator? */
11639                 bScreen *screen;
11640                 for(screen= main->screen.first; screen; screen= screen->id.next) {
11641                         ScrArea *sa;
11642                         /* add regions */
11643                         for(sa= screen->areabase.first; sa; sa= sa->next) {
11644                                 SpaceLink *sl= sa->spacedata.first;
11645                                 if(sl->spacetype==SPACE_IMAGE) {
11646                                         ARegion *ar;
11647                                         for (ar=sa->regionbase.first; ar; ar= ar->next) {
11648                                                 if(ar->regiontype == RGN_TYPE_WINDOW) {
11649                                                         View2D *v2d= &ar->v2d;
11650                                                         v2d->minzoom= v2d->maxzoom= v2d->scroll= v2d->keeptot= v2d->keepzoom= v2d->keepofs= v2d->align= 0;
11651                                                 }
11652                                         }
11653                                 }
11654                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11655                                         if(sl->spacetype==SPACE_IMAGE) {
11656                                                 ARegion *ar;
11657                                                 for (ar=sl->regionbase.first; ar; ar= ar->next) {
11658                                                         if(ar->regiontype == RGN_TYPE_WINDOW) {
11659                                                                 View2D *v2d= &ar->v2d;
11660                                                                 v2d->minzoom= v2d->maxzoom= v2d->scroll= v2d->keeptot= v2d->keepzoom= v2d->keepofs= v2d->align= 0;
11661                                                         }
11662                                                 }
11663                                         }
11664                                 }
11665                         }
11666                 }
11667 
11668                 {
11669                         /* Initialize texture point density curve falloff */
11670                         Tex *tex;
11671                         for(tex= main->tex.first; tex; tex= tex->id.next) {
11672                                 if(tex->pd) {
11673                                         if (tex->pd->falloff_speed_scale == 0.0)
11674                                                 tex->pd->falloff_speed_scale = 100.0;
11675 
11676                                         if (!tex->pd->falloff_curve) {
11677                                                 tex->pd->falloff_curve = curvemapping_add(1, 0, 0, 1, 1);
11678 
11679                                                 tex->pd->falloff_curve->preset = CURVE_PRESET_LINE;
11680                                                 tex->pd->falloff_curve->cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
11681                                                 curvemap_reset(tex->pd->falloff_curve->cm, &tex->pd->falloff_curve->clipr, tex->pd->falloff_curve->preset, CURVEMAP_SLOPE_POSITIVE);
11682                                                 curvemapping_changed(tex->pd->falloff_curve, 0);
11683                                         }
11684                                 }
11685                         }
11686                 }
11687 
11688                 {
11689                         /* add default value for behind strength of camera actuator */
11690                         Object *ob;
11691                         bActuator *act;
11692                         for(ob = main->object.first; ob; ob= ob->id.next) {
11693                                 for(act= ob->actuators.first; act; act= act->next) {
11694                                         if (act->type == ACT_CAMERA) {
11695                                                 bCameraActuator *ba= act->data;
11696 
11697                                                 ba->damping = 1.0/32.0;
11698                                         }
11699                                 }
11700                         }
11701                 }
11702 
11703                 {
11704                         ParticleSettings *part;
11705                         for(part = main->particle.first; part; part = part->id.next) {
11706                                 /* Initialize particle billboard scale */
11707                                 part->bb_size[0] = part->bb_size[1] = 1.0f;
11708                         }
11709                 }
11710         }
11711         
11712         /* put compatibility code here until next subversion bump */
11713 
11714         {
11715         
11716         }
11717         
11718         /* WATCH IT!!!: pointers from libdata have not been converted yet here! */
11719         /* WATCH IT 2!: Userdef struct init has to be in editors/interface/resources.c! */
11720 
11721         /* don't forget to set version number in blender.c! */
11722 }
11723 
11724 #if 0 // XXX: disabled for now... we still don't have this in the right place in the loading code for it to work
11725 static void do_versions_after_linking(FileData *fd, Library *lib, Main *main)
11726 {
11727         /* old Animation System (using IPO's) needs to be converted to the new Animato system */
11728         if(main->versionfile < 250)
11729                 do_versions_ipos_to_animato(main);
11730 }
11731 #endif
11732 
11733 static void lib_link_all(FileData *fd, Main *main)
11734 {
11735         oldnewmap_sort(fd);
11736         
11737         lib_link_windowmanager(fd, main);
11738         lib_link_screen(fd, main);
11739         lib_link_scene(fd, main);
11740         lib_link_object(fd, main);
11741         lib_link_curve(fd, main);
11742         lib_link_mball(fd, main);
11743         lib_link_material(fd, main);
11744         lib_link_texture(fd, main);
11745         lib_link_image(fd, main);
11746         lib_link_ipo(fd, main);         // XXX depreceated... still needs to be maintained for version patches still
11747         lib_link_key(fd, main);
11748         lib_link_world(fd, main);
11749         lib_link_lamp(fd, main);
11750         lib_link_latt(fd, main);
11751         lib_link_text(fd, main);
11752         lib_link_camera(fd, main);
11753         lib_link_sound(fd, main);
11754         lib_link_group(fd, main);
11755         lib_link_armature(fd, main);
11756         lib_link_action(fd, main);
11757         lib_link_vfont(fd, main);
11758         lib_link_nodetree(fd, main);    /* has to be done after scene/materials, this will verify group nodes */
11759         lib_link_brush(fd, main);
11760         lib_link_particlesettings(fd, main);
11761 
11762         lib_link_mesh(fd, main);                /* as last: tpage images with users at zero */
11763 
11764         lib_link_library(fd, main);             /* only init users */
11765 }
11766 
11767 static void direct_link_keymapitem(FileData *fd, wmKeyMapItem *kmi)
11768 {
11769         kmi->properties= newdataadr(fd, kmi->properties);
11770         if(kmi->properties)
11771                 IDP_DirectLinkProperty(kmi->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
11772         kmi->ptr= NULL;
11773         kmi->flag &= ~KMI_UPDATE;
11774 }
11775 
11776 static BHead *read_userdef(BlendFileData *bfd, FileData *fd, BHead *bhead)
11777 {
11778         UserDef *user;
11779         wmKeyMap *keymap;
11780         wmKeyMapItem *kmi;
11781         wmKeyMapDiffItem *kmdi;
11782 
11783         bfd->user= user= read_struct(fd, bhead, "user def");
11784 
11785         /* read all data into fd->datamap */
11786         bhead= read_data_into_oldnewmap(fd, bhead, "user def");
11787 
11788         if(user->keymaps.first) {
11789                 /* backwards compatibility */
11790                 user->user_keymaps= user->keymaps;
11791                 user->keymaps.first= user->keymaps.last= NULL;
11792         }
11793 
11794         link_list(fd, &user->themes);
11795         link_list(fd, &user->user_keymaps);
11796         link_list(fd, &user->addons);
11797 
11798         for(keymap=user->user_keymaps.first; keymap; keymap=keymap->next) {
11799                 keymap->modal_items= NULL;
11800                 keymap->poll= NULL;
11801                 keymap->flag &= ~KEYMAP_UPDATE;
11802 
11803                 link_list(fd, &keymap->diff_items);
11804                 link_list(fd, &keymap->items);
11805                 
11806                 for(kmdi=keymap->diff_items.first; kmdi; kmdi=kmdi->next) {
11807                         kmdi->remove_item= newdataadr(fd, kmdi->remove_item);
11808                         kmdi->add_item= newdataadr(fd, kmdi->add_item);
11809 
11810                         if(kmdi->remove_item)
11811                                 direct_link_keymapitem(fd, kmdi->remove_item);
11812                         if(kmdi->add_item)
11813                                 direct_link_keymapitem(fd, kmdi->add_item);
11814                 }
11815 
11816                 for(kmi=keymap->items.first; kmi; kmi=kmi->next)
11817                         direct_link_keymapitem(fd, kmi);
11818         }
11819 
11820         // XXX
11821         user->uifonts.first= user->uifonts.last= NULL;
11822         
11823         link_list(fd, &user->uistyles);
11824 
11825         /* free fd->datamap again */
11826         oldnewmap_free_unused(fd->datamap);
11827         oldnewmap_clear(fd->datamap);
11828 
11829         return bhead;
11830 }
11831 
11832 BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath)
11833 {
11834         BHead *bhead= blo_firstbhead(fd);
11835         BlendFileData *bfd;
11836 
11837         bfd= MEM_callocN(sizeof(BlendFileData), "blendfiledata");
11838         bfd->main= MEM_callocN(sizeof(Main), "main");
11839         BLI_addtail(&fd->mainlist, bfd->main);
11840 
11841         bfd->main->versionfile= fd->fileversion;
11842         
11843         bfd->type= BLENFILETYPE_BLEND;
11844         strncpy(bfd->main->name, filepath, sizeof(bfd->main->name)-1);
11845 
11846         while(bhead) {
11847                 switch(bhead->code) {
11848                 case DATA:
11849                 case DNA1:
11850                 case TEST: /* used as preview since 2.5x */
11851                 case REND:
11852                         bhead = blo_nextbhead(fd, bhead);
11853                         break;
11854                 case GLOB:
11855                         bhead= read_global(bfd, fd, bhead);
11856                         break;
11857                 case USER:
11858                         bhead= read_userdef(bfd, fd, bhead);
11859                         break;
11860                 case ENDB:
11861                         bhead = NULL;
11862                         break;
11863 
11864                 case ID_LI:
11865                         /* skip library datablocks in undo, this works together with
11866                            BLO_read_from_memfile, where the old main->library is restored
11867                            overwriting  the libraries from the memory file. previously
11868                            it did not save ID_LI/ID_ID blocks in this case, but they are
11869                            needed to make quit.blend recover them correctly. */
11870                         if(fd->memfile)
11871                                 bhead= blo_nextbhead(fd, bhead);
11872                         else
11873                                 bhead= read_libblock(fd, bfd->main, bhead, LIB_LOCAL, NULL);
11874                         break;
11875                 case ID_ID:
11876                         /* same as above */
11877                         if(fd->memfile)
11878                                 bhead= blo_nextbhead(fd, bhead);
11879                         else
11880                                 /* always adds to the most recently loaded
11881                                  * ID_LI block, see direct_link_library.
11882                                  * this is part of the file format definition. */
11883                                 bhead = read_libblock(fd, fd->mainlist.last, bhead, LIB_READ+LIB_EXTERN, NULL);
11884                         break;
11885                         
11886                         /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
11887                 case ID_SCRN:
11888                         bhead->code= ID_SCR;
11889                         /* deliberate pass on to default */
11890                 default:
11891                         bhead = read_libblock(fd, bfd->main, bhead, LIB_LOCAL, NULL);
11892                 }
11893         }
11894 
11895         /* do before read_libraries, but skip undo case */
11896 //      if(fd->memfile==NULL) (the mesh shuffle hacks don't work yet? ton)
11897                 do_versions(fd, NULL, bfd->main);
11898 
11899         read_libraries(fd, &fd->mainlist);
11900         
11901         blo_join_main(&fd->mainlist);
11902 
11903         lib_link_all(fd, bfd->main);
11904         //do_versions_after_linking(fd, NULL, bfd->main); // XXX: not here (or even in this function at all)! this causes crashes on many files - Aligorith (July 04, 2010)
11905         lib_verify_nodetree(bfd->main, TRUE);
11906         fix_relpaths_library(fd->relabase, bfd->main); /* make all relative paths, relative to the open blend file */
11907         
11908         link_global(fd, bfd);   /* as last */
11909         
11910         return bfd;
11911 }
11912 
11913 /* ************* APPEND LIBRARY ************** */
11914 
11915 struct bheadsort {
11916         BHead *bhead;
11917         void *old;
11918 };
11919 
11920 static int verg_bheadsort(const void *v1, const void *v2)
11921 {
11922         const struct bheadsort *x1=v1, *x2=v2;
11923         
11924         if( x1->old > x2->old) return 1;
11925         else if( x1->old < x2->old) return -1;
11926         return 0;
11927 }
11928 
11929 static void sort_bhead_old_map(FileData *fd)
11930 {
11931         BHead *bhead;
11932         struct bheadsort *bhs;
11933         int tot= 0;
11934         
11935         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead))
11936                 tot++;
11937         
11938         fd->tot_bheadmap= tot;
11939         if(tot==0) return;
11940         
11941         bhs= fd->bheadmap= MEM_mallocN(tot*sizeof(struct bheadsort), "bheadsort");
11942         
11943         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead), bhs++) {
11944                 bhs->bhead= bhead;
11945                 bhs->old= bhead->old;
11946         }
11947         
11948         qsort(fd->bheadmap, tot, sizeof(struct bheadsort), verg_bheadsort);
11949                 
11950 }
11951 
11952 static BHead *find_previous_lib(FileData *fd, BHead *bhead)
11953 {
11954         /* skip library datablocks in undo, see comment in read_libblock */
11955         if(fd->memfile)
11956                 return NULL;
11957 
11958         for (; bhead; bhead= blo_prevbhead(fd, bhead))
11959                 if (bhead->code==ID_LI)
11960                         break;
11961 
11962         return bhead;
11963 }
11964 
11965 static BHead *find_bhead(FileData *fd, void *old)
11966 {
11967 #if 0
11968         BHead *bhead;
11969 #endif
11970         struct bheadsort *bhs, bhs_s;
11971         
11972         if (!old)
11973                 return NULL;
11974 
11975         if (fd->bheadmap==NULL)
11976                 sort_bhead_old_map(fd);
11977         
11978         bhs_s.old= old;
11979         bhs= bsearch(&bhs_s, fd->bheadmap, fd->tot_bheadmap, sizeof(struct bheadsort), verg_bheadsort);
11980 
11981         if(bhs)
11982                 return bhs->bhead;
11983         
11984 #if 0
11985         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead))
11986                 if (bhead->old==old)
11987                         return bhead;
11988 #endif
11989 
11990         return NULL;
11991 }
11992 
11993 char *bhead_id_name(FileData *fd, BHead *bhead)
11994 {
11995         return ((char *)(bhead+1)) + fd->id_name_offs;
11996 }
11997 
11998 static ID *is_yet_read(FileData *fd, Main *mainvar, BHead *bhead)
11999 {
12000         const char *idname= bhead_id_name(fd, bhead);
12001         /* which_libbase can be NULL, intentionally not using idname+2 */
12002         return BLI_findstring(which_libbase(mainvar, GS(idname)), idname, offsetof(ID, name));
12003 }
12004 
12005 static void expand_doit(FileData *fd, Main *mainvar, void *old)
12006 {
12007         BHead *bhead;
12008         ID *id;
12009 
12010         bhead= find_bhead(fd, old);
12011         if(bhead) {
12012                         /* from another library? */
12013                 if(bhead->code==ID_ID) {
12014                         BHead *bheadlib= find_previous_lib(fd, bhead);
12015 
12016                         if(bheadlib) {
12017                                 Library *lib= read_struct(fd, bheadlib, "Library");
12018                                 Main *ptr= blo_find_main(fd, &fd->mainlist, lib->name, fd->relabase);
12019 
12020                                 id= is_yet_read(fd, ptr, bhead);
12021 
12022                                 if(id==NULL) {
12023                                         read_libblock(fd, ptr, bhead, LIB_READ+LIB_INDIRECT, NULL);
12024                                         // commented because this can print way too much
12025                                         // if(G.f & G_DEBUG) printf("expand_doit: other lib %s\n", lib->name);
12026                                         
12027                                         /* for outliner dependency only */
12028                                         ptr->curlib->parent= mainvar->curlib;
12029                                 }
12030                                 else {
12031                                         /* The line below was commented by Ton (I assume), when Hos did the merge from the orange branch. rev 6568
12032                                          * This line is NEEDED, the case is that you have 3 blend files...
12033                                          * user.blend, lib.blend and lib_indirect.blend - if user.blend already references a "tree" from
12034                                          * lib_indirect.blend but lib.blend does too, linking in a Scene or Group from lib.blend can result in an
12035                                          * empty without the dupli group referenced. Once you save and reload the group would appier. - Campbell */
12036                                         /* This crashes files, must look further into it */
12037                                         
12038                                         /* Update: the issue is that in file reading, the oldnewmap is OK, but for existing data, it has to be
12039                                            inserted in the map to be found! */
12040                                         if(id->flag & LIB_PRE_EXISTING)
12041                                                 oldnewmap_insert(fd->libmap, bhead->old, id, 1);
12042                                         
12043                                         change_idid_adr_fd(fd, bhead->old, id);
12044                                         // commented because this can print way too much
12045                                         // if(G.f & G_DEBUG) printf("expand_doit: already linked: %s lib: %s\n", id->name, lib->name);
12046                                 }
12047                                 
12048                                 MEM_freeN(lib);
12049                         }
12050                 }
12051                 else {
12052                         id= is_yet_read(fd, mainvar, bhead);
12053                         if(id==NULL) {
12054                                 read_libblock(fd, mainvar, bhead, LIB_TESTIND, NULL);
12055                         }
12056                         else {
12057                                 /* this is actually only needed on UI call? when ID was already read before, and another append
12058                                    happens which invokes same ID... in that case the lookup table needs this entry */
12059                                 oldnewmap_insert(fd->libmap, bhead->old, id, 1);
12060                                 // commented because this can print way too much
12061                                 // if(G.f & G_DEBUG) printf("expand: already read %s\n", id->name);
12062                         }
12063                 }
12064         }
12065 }
12066 
12067 
12068 
12069 // XXX depreceated - old animation system
12070 static void expand_ipo(FileData *fd, Main *mainvar, Ipo *ipo)
12071 {
12072         IpoCurve *icu;
12073         for(icu= ipo->curve.first; icu; icu= icu->next) {
12074                 if(icu->driver)
12075                         expand_doit(fd, mainvar, icu->driver->ob);
12076         }
12077 }
12078 
12079 // XXX depreceated - old animation system
12080 static void expand_constraint_channels(FileData *fd, Main *mainvar, ListBase *chanbase)
12081 {
12082         bConstraintChannel *chan;
12083         for (chan=chanbase->first; chan; chan=chan->next) {
12084                 expand_doit(fd, mainvar, chan->ipo);
12085         }
12086 }
12087 
12088 static void expand_fmodifiers(FileData *fd, Main *mainvar, ListBase *list)
12089 {
12090         FModifier *fcm;
12091         
12092         for (fcm= list->first; fcm; fcm= fcm->next) {
12093                 /* library data for specific F-Modifier types */
12094                 switch (fcm->type) {
12095                         case FMODIFIER_TYPE_PYTHON:
12096                         {
12097                                 FMod_Python *data= (FMod_Python *)fcm->data;
12098                                 
12099                                 expand_doit(fd, mainvar, data->script);
12100                         }
12101                                 break;
12102                 }
12103         }
12104 }
12105 
12106 static void expand_fcurves(FileData *fd, Main *mainvar, ListBase *list)
12107 {
12108         FCurve *fcu;
12109         
12110         for (fcu= list->first; fcu; fcu= fcu->next) {
12111                 /* Driver targets if there is a driver */
12112                 if (fcu->driver) {
12113                         ChannelDriver *driver= fcu->driver;
12114                         DriverVar *dvar;
12115                         
12116                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
12117                                 DRIVER_TARGETS_LOOPER(dvar) 
12118                                 {
12119                                         // TODO: only expand those that are going to get used?
12120                                         expand_doit(fd, mainvar, dtar->id);
12121                                 }
12122                                 DRIVER_TARGETS_LOOPER_END
12123                         }
12124                 }
12125                 
12126                 /* F-Curve Modifiers */
12127                 expand_fmodifiers(fd, mainvar, &fcu->modifiers);
12128         }
12129 }
12130 
12131 static void expand_action(FileData *fd, Main *mainvar, bAction *act)
12132 {
12133         bActionChannel *chan;
12134         
12135         // XXX depreceated - old animation system --------------
12136         for (chan=act->chanbase.first; chan; chan=chan->next) {
12137                 expand_doit(fd, mainvar, chan->ipo);
12138                 expand_constraint_channels(fd, mainvar, &chan->constraintChannels);
12139         }
12140         // ---------------------------------------------------
12141         
12142         /* F-Curves in Action */
12143         expand_fcurves(fd, mainvar, &act->curves);
12144 }
12145 
12146 static void expand_keyingsets(FileData *fd, Main *mainvar, ListBase *list)
12147 {
12148         KeyingSet *ks;
12149         KS_Path *ksp;
12150         
12151         /* expand the ID-pointers in KeyingSets's paths */
12152         for (ks= list->first; ks; ks= ks->next) {
12153                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
12154                         expand_doit(fd, mainvar, ksp->id);
12155                 }
12156         }
12157 }
12158 
12159 static void expand_animdata_nlastrips(FileData *fd, Main *mainvar, ListBase *list)
12160 {
12161         NlaStrip *strip;
12162         
12163         for (strip= list->first; strip; strip= strip->next) {
12164                 /* check child strips */
12165                 expand_animdata_nlastrips(fd, mainvar, &strip->strips);
12166                 
12167                 /* check F-Curves */
12168                 expand_fcurves(fd, mainvar, &strip->fcurves);
12169                 
12170                 /* check F-Modifiers */
12171                 expand_fmodifiers(fd, mainvar, &strip->modifiers);
12172                 
12173                 /* relink referenced action */
12174                 expand_doit(fd, mainvar, strip->act);
12175         }
12176 }
12177 
12178 static void expand_animdata(FileData *fd, Main *mainvar, AnimData *adt)
12179 {
12180         NlaTrack *nlt;
12181         
12182         /* own action */
12183         expand_doit(fd, mainvar, adt->action);
12184         expand_doit(fd, mainvar, adt->tmpact);
12185         
12186         /* drivers - assume that these F-Curves have driver data to be in this list... */
12187         expand_fcurves(fd, mainvar, &adt->drivers);
12188         
12189         /* nla-data - referenced actions */
12190         for (nlt= adt->nla_tracks.first; nlt; nlt= nlt->next) 
12191                 expand_animdata_nlastrips(fd, mainvar, &nlt->strips);
12192 }       
12193 
12194 static void expand_particlesettings(FileData *fd, Main *mainvar, ParticleSettings *part)
12195 {
12196         int a;
12197 
12198         expand_doit(fd, mainvar, part->dup_ob);
12199         expand_doit(fd, mainvar, part->dup_group);
12200         expand_doit(fd, mainvar, part->eff_group);
12201         expand_doit(fd, mainvar, part->bb_ob);
12202         
12203         if(part->adt)
12204                 expand_animdata(fd, mainvar, part->adt);
12205 
12206         for(a=0; a<MAX_MTEX; a++) {
12207                 if(part->mtex[a]) {
12208                         expand_doit(fd, mainvar, part->mtex[a]->tex);
12209                         expand_doit(fd, mainvar, part->mtex[a]->object);
12210                 }
12211         }
12212 }
12213 
12214 static void expand_group(FileData *fd, Main *mainvar, Group *group)
12215 {
12216         GroupObject *go;
12217         
12218         for(go= group->gobject.first; go; go= go->next) {
12219                 expand_doit(fd, mainvar, go->ob);
12220         }
12221 }
12222 
12223 static void expand_key(FileData *fd, Main *mainvar, Key *key)
12224 {
12225         expand_doit(fd, mainvar, key->ipo); // XXX depreceated - old animation system
12226         
12227         if(key->adt)
12228                 expand_animdata(fd, mainvar, key->adt);
12229 }
12230 
12231 static void expand_nodetree(FileData *fd, Main *mainvar, bNodeTree *ntree)
12232 {
12233         bNode *node;
12234         
12235         if(ntree->adt)
12236                 expand_animdata(fd, mainvar, ntree->adt);
12237                 
12238         if(ntree->gpd)
12239                 expand_doit(fd, mainvar, ntree->gpd);
12240         
12241         for(node= ntree->nodes.first; node; node= node->next)
12242                 if(node->id && node->type!=CMP_NODE_R_LAYERS)
12243                         expand_doit(fd, mainvar, node->id);
12244 
12245 }
12246 
12247 static void expand_texture(FileData *fd, Main *mainvar, Tex *tex)
12248 {
12249         expand_doit(fd, mainvar, tex->ima);
12250         expand_doit(fd, mainvar, tex->ipo); // XXX depreceated - old animation system
12251         
12252         if(tex->adt)
12253                 expand_animdata(fd, mainvar, tex->adt);
12254         
12255         if(tex->nodetree)
12256                 expand_nodetree(fd, mainvar, tex->nodetree);
12257 }
12258 
12259 static void expand_brush(FileData *fd, Main *mainvar, Brush *brush)
12260 {
12261         expand_doit(fd, mainvar, brush->mtex.tex);
12262         expand_doit(fd, mainvar, brush->clone.image);
12263 }
12264 
12265 static void expand_material(FileData *fd, Main *mainvar, Material *ma)
12266 {
12267         int a;
12268 
12269         for(a=0; a<MAX_MTEX; a++) {
12270                 if(ma->mtex[a]) {
12271                         expand_doit(fd, mainvar, ma->mtex[a]->tex);
12272                         expand_doit(fd, mainvar, ma->mtex[a]->object);
12273                 }
12274         }
12275         
12276         expand_doit(fd, mainvar, ma->ipo); // XXX depreceated - old animation system
12277         
12278         if(ma->adt)
12279                 expand_animdata(fd, mainvar, ma->adt);
12280         
12281         if(ma->nodetree)
12282                 expand_nodetree(fd, mainvar, ma->nodetree);
12283         
12284         if(ma->group)
12285                 expand_doit(fd, mainvar, ma->group);
12286 }
12287 
12288 static void expand_lamp(FileData *fd, Main *mainvar, Lamp *la)
12289 {
12290         int a;
12291 
12292         for(a=0; a<MAX_MTEX; a++) {
12293                 if(la->mtex[a]) {
12294                         expand_doit(fd, mainvar, la->mtex[a]->tex);
12295                         expand_doit(fd, mainvar, la->mtex[a]->object);
12296                 }
12297         }
12298         
12299         expand_doit(fd, mainvar, la->ipo); // XXX depreceated - old animation system
12300         
12301         if (la->adt)
12302                 expand_animdata(fd, mainvar, la->adt);
12303 }
12304 
12305 static void expand_lattice(FileData *fd, Main *mainvar, Lattice *lt)
12306 {
12307         expand_doit(fd, mainvar, lt->ipo); // XXX depreceated - old animation system
12308         expand_doit(fd, mainvar, lt->key);
12309         
12310         if (lt->adt)
12311                 expand_animdata(fd, mainvar, lt->adt);
12312 }
12313 
12314 
12315 static void expand_world(FileData *fd, Main *mainvar, World *wrld)
12316 {
12317         int a;
12318 
12319         for(a=0; a<MAX_MTEX; a++) {
12320                 if(wrld->mtex[a]) {
12321                         expand_doit(fd, mainvar, wrld->mtex[a]->tex);
12322                         expand_doit(fd, mainvar, wrld->mtex[a]->object);
12323                 }
12324         }
12325         
12326         expand_doit(fd, mainvar, wrld->ipo); // XXX depreceated - old animation system
12327         
12328         if (wrld->adt)
12329                 expand_animdata(fd, mainvar, wrld->adt);
12330 }
12331 
12332 
12333 static void expand_mball(FileData *fd, Main *mainvar, MetaBall *mb)
12334 {
12335         int a;
12336 
12337         for(a=0; a<mb->totcol; a++) {
12338                 expand_doit(fd, mainvar, mb->mat[a]);
12339         }
12340         
12341         if(mb->adt)
12342                 expand_animdata(fd, mainvar, mb->adt);
12343 }
12344 
12345 static void expand_curve(FileData *fd, Main *mainvar, Curve *cu)
12346 {
12347         int a;
12348 
12349         for(a=0; a<cu->totcol; a++) {
12350                 expand_doit(fd, mainvar, cu->mat[a]);
12351         }
12352         
12353         expand_doit(fd, mainvar, cu->vfont);
12354         expand_doit(fd, mainvar, cu->vfontb);   
12355         expand_doit(fd, mainvar, cu->vfonti);
12356         expand_doit(fd, mainvar, cu->vfontbi);
12357         expand_doit(fd, mainvar, cu->key);
12358         expand_doit(fd, mainvar, cu->ipo); // XXX depreceated - old animation system
12359         expand_doit(fd, mainvar, cu->bevobj);
12360         expand_doit(fd, mainvar, cu->taperobj);
12361         expand_doit(fd, mainvar, cu->textoncurve);
12362         
12363         if(cu->adt)
12364                 expand_animdata(fd, mainvar, cu->adt);
12365 }
12366 
12367 static void expand_mesh(FileData *fd, Main *mainvar, Mesh *me)
12368 {
12369         CustomDataLayer *layer;
12370         MTFace *mtf;
12371         TFace *tf;
12372         int a, i;
12373         
12374         if(me->adt)
12375                 expand_animdata(fd, mainvar, me->adt);
12376                 
12377         for(a=0; a<me->totcol; a++) {
12378                 expand_doit(fd, mainvar, me->mat[a]);
12379         }
12380 
12381         expand_doit(fd, mainvar, me->key);
12382         expand_doit(fd, mainvar, me->texcomesh);
12383 
12384         if(me->tface) {
12385                 tf= me->tface;
12386                 for(i=0; i<me->totface; i++, tf++)
12387                         if(tf->tpage)
12388                                 expand_doit(fd, mainvar, tf->tpage);
12389         }
12390 
12391         for(a=0; a<me->fdata.totlayer; a++) {
12392                 layer= &me->fdata.layers[a];
12393 
12394                 if(layer->type == CD_MTFACE) {
12395                         mtf= (MTFace*)layer->data;
12396                         for(i=0; i<me->totface; i++, mtf++)
12397                                 if(mtf->tpage)
12398                                         expand_doit(fd, mainvar, mtf->tpage);
12399                 }
12400         }
12401 }
12402 
12403 /* temp struct used to transport needed info to expand_constraint_cb() */
12404 typedef struct tConstraintExpandData {
12405         FileData *fd;
12406         Main *mainvar;
12407 } tConstraintExpandData;
12408 /* callback function used to expand constraint ID-links */
12409 static void expand_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, void *userdata)
12410 {
12411         tConstraintExpandData *ced= (tConstraintExpandData *)userdata;
12412         expand_doit(ced->fd, ced->mainvar, *idpoin);
12413 }
12414 
12415 static void expand_constraints(FileData *fd, Main *mainvar, ListBase *lb)
12416 {
12417         tConstraintExpandData ced;
12418         bConstraint *curcon;
12419         
12420         /* relink all ID-blocks used by the constraints */
12421         ced.fd= fd;
12422         ced.mainvar= mainvar;
12423         
12424         id_loop_constraints(lb, expand_constraint_cb, &ced);
12425         
12426         /* depreceated manual expansion stuff */
12427         for (curcon=lb->first; curcon; curcon=curcon->next) {
12428                 if (curcon->ipo)
12429                         expand_doit(fd, mainvar, curcon->ipo); // XXX depreceated - old animation system
12430         }
12431 }
12432 
12433 static void expand_bones(FileData *fd, Main *mainvar, Bone *bone)
12434 {
12435         Bone *curBone;
12436 
12437         for (curBone = bone->childbase.first; curBone; curBone=curBone->next) {
12438                 expand_bones(fd, mainvar, curBone);
12439         }
12440 
12441 }
12442 
12443 static void expand_pose(FileData *fd, Main *mainvar, bPose *pose)
12444 {
12445         bPoseChannel *chan;
12446 
12447         if (!pose)
12448                 return;
12449 
12450         for (chan = pose->chanbase.first; chan; chan=chan->next) {
12451                 expand_constraints(fd, mainvar, &chan->constraints);
12452                 expand_doit(fd, mainvar, chan->custom);
12453         }
12454 }
12455 
12456 static void expand_armature(FileData *fd, Main *mainvar, bArmature *arm)
12457 {
12458         Bone *curBone;
12459 
12460         if(arm->adt)
12461                 expand_animdata(fd, mainvar, arm->adt);
12462 
12463         for (curBone = arm->bonebase.first; curBone; curBone=curBone->next) {
12464                 expand_bones(fd, mainvar, curBone);
12465         }
12466 }
12467 
12468 static void expand_object_expandModifiers(void *userData, Object *UNUSED(ob),
12469                                                                                           ID **idpoin)
12470 {
12471         struct { FileData *fd; Main *mainvar; } *data= userData;
12472 
12473         FileData *fd= data->fd;
12474         Main *mainvar= data->mainvar;
12475 
12476         expand_doit(fd, mainvar, *idpoin);
12477 }
12478 
12479 static void expand_object(FileData *fd, Main *mainvar, Object *ob)
12480 {
12481         ParticleSystem *psys;
12482         bSensor *sens;
12483         bController *cont;
12484         bActuator *act;
12485         bActionStrip *strip;
12486         PartEff *paf;
12487         int a;
12488 
12489         expand_doit(fd, mainvar, ob->data);
12490 
12491         /* expand_object_expandModifier() */
12492         if(ob->modifiers.first) {
12493                 struct { FileData *fd; Main *mainvar; } data;
12494                 data.fd= fd;
12495                 data.mainvar= mainvar;
12496 
12497                 modifiers_foreachIDLink(ob, expand_object_expandModifiers, (void *)&data);
12498         }
12499 
12500         expand_pose(fd, mainvar, ob->pose);
12501         expand_doit(fd, mainvar, ob->poselib);
12502         expand_constraints(fd, mainvar, &ob->constraints);
12503         
12504         expand_doit(fd, mainvar, ob->gpd);
12505         
12506 // XXX depreceated - old animation system (for version patching only) 
12507         expand_doit(fd, mainvar, ob->ipo);
12508         expand_doit(fd, mainvar, ob->action);
12509         
12510         expand_constraint_channels(fd, mainvar, &ob->constraintChannels);
12511 
12512         for (strip=ob->nlastrips.first; strip; strip=strip->next){
12513                 expand_doit(fd, mainvar, strip->object);
12514                 expand_doit(fd, mainvar, strip->act);
12515                 expand_doit(fd, mainvar, strip->ipo);
12516         }
12517 // XXX depreceated - old animation system (for version patching only)
12518         
12519         if(ob->adt)
12520                 expand_animdata(fd, mainvar, ob->adt);
12521         
12522         for(a=0; a<ob->totcol; a++) {
12523                 expand_doit(fd, mainvar, ob->mat[a]);
12524         }
12525         
12526         paf = give_parteff(ob);
12527         if (paf && paf->group) 
12528                 expand_doit(fd, mainvar, paf->group);
12529 
12530         if(ob->dup_group)
12531                 expand_doit(fd, mainvar, ob->dup_group);
12532         
12533         if(ob->proxy)
12534                 expand_doit(fd, mainvar, ob->proxy);
12535         if(ob->proxy_group)
12536                 expand_doit(fd, mainvar, ob->proxy_group);
12537 
12538         for(psys=ob->particlesystem.first; psys; psys=psys->next)
12539                 expand_doit(fd, mainvar, psys->part);
12540 
12541         sens= ob->sensors.first;
12542         while(sens) {
12543                 if(sens->type==SENS_TOUCH) {
12544                         bTouchSensor *ts= sens->data;
12545                         expand_doit(fd, mainvar, ts->ma);
12546                 }
12547                 else if(sens->type==SENS_MESSAGE) {
12548                         bMessageSensor *ms= sens->data;
12549                         expand_doit(fd, mainvar, ms->fromObject);
12550                 }
12551                 sens= sens->next;
12552         }
12553 
12554         cont= ob->controllers.first;
12555         while(cont) {
12556                 if(cont->type==CONT_PYTHON) {
12557                         bPythonCont *pc= cont->data;
12558                         expand_doit(fd, mainvar, pc->text);
12559                 }
12560                 cont= cont->next;
12561         }
12562 
12563         act= ob->actuators.first;
12564         while(act) {
12565                 if(act->type==ACT_SOUND) {
12566                         bSoundActuator *sa= act->data;
12567                         expand_doit(fd, mainvar, sa->sound);
12568                 }
12569                 else if(act->type==ACT_CAMERA) {
12570                         bCameraActuator *ca= act->data;
12571                         expand_doit(fd, mainvar, ca->ob);
12572                 }
12573                 else if(act->type==ACT_EDIT_OBJECT) {
12574                         bEditObjectActuator *eoa= act->data;
12575                         if(eoa) {
12576                                 expand_doit(fd, mainvar, eoa->ob);
12577                                 expand_doit(fd, mainvar, eoa->me);
12578                         }
12579                 }
12580                 else if(act->type==ACT_OBJECT) {
12581                         bObjectActuator *oa= act->data;
12582                         expand_doit(fd, mainvar, oa->reference);
12583                 }
12584                 else if(act->type==ACT_ADD_OBJECT) {
12585                         bAddObjectActuator *aoa= act->data;
12586                         expand_doit(fd, mainvar, aoa->ob);
12587                 }
12588                 else if(act->type==ACT_SCENE) {
12589                         bSceneActuator *sa= act->data;
12590                         expand_doit(fd, mainvar, sa->camera);
12591                         expand_doit(fd, mainvar, sa->scene);
12592                 }
12593                 else if(act->type==ACT_2DFILTER) {
12594                         bTwoDFilterActuator *tdfa= act->data;
12595                         expand_doit(fd, mainvar, tdfa->text);
12596                 }
12597                 else if(act->type==ACT_ACTION) {
12598                         bActionActuator *aa= act->data;
12599                         expand_doit(fd, mainvar, aa->act);
12600                 }
12601                 else if(act->type==ACT_SHAPEACTION) {
12602                         bActionActuator *aa= act->data;
12603                         expand_doit(fd, mainvar, aa->act);
12604                 }
12605                 else if(act->type==ACT_PROPERTY) {
12606                         bPropertyActuator *pa= act->data;
12607                         expand_doit(fd, mainvar, pa->ob);
12608                 }
12609                 else if(act->type==ACT_MESSAGE) {
12610                         bMessageActuator *ma= act->data;
12611                         expand_doit(fd, mainvar, ma->toObject);
12612                 }
12613                 else if(act->type==ACT_PARENT) {
12614                         bParentActuator *pa= act->data;
12615                         expand_doit(fd, mainvar, pa->ob);
12616                 }
12617                 else if(act->type==ACT_ARMATURE) {
12618                         bArmatureActuator *arma= act->data;
12619                         expand_doit(fd, mainvar, arma->target);
12620                 }
12621                 act= act->next;
12622         }
12623 
12624         if(ob->pd && ob->pd->tex)
12625                 expand_doit(fd, mainvar, ob->pd->tex);
12626         
12627 }
12628 
12629 static void expand_scene(FileData *fd, Main *mainvar, Scene *sce)
12630 {
12631         Base *base;
12632         SceneRenderLayer *srl;
12633 
12634         for(base= sce->base.first; base; base= base->next) {
12635                 expand_doit(fd, mainvar, base->object);
12636         }
12637         expand_doit(fd, mainvar, sce->camera);
12638         expand_doit(fd, mainvar, sce->world);
12639         
12640         if(sce->adt)
12641                 expand_animdata(fd, mainvar, sce->adt);
12642         expand_keyingsets(fd, mainvar, &sce->keyingsets);
12643         
12644         if(sce->set)
12645                 expand_doit(fd, mainvar, sce->set);
12646         
12647         if(sce->nodetree)
12648                 expand_nodetree(fd, mainvar, sce->nodetree);
12649         
12650         for(srl= sce->r.layers.first; srl; srl= srl->next) {
12651                 expand_doit(fd, mainvar, srl->mat_override);
12652                 expand_doit(fd, mainvar, srl->light_override);
12653         }
12654 
12655         if(sce->r.dometext)
12656                 expand_doit(fd, mainvar, sce->gm.dome.warptext);
12657                 
12658         if(sce->gpd)
12659                 expand_doit(fd, mainvar, sce->gpd);
12660 
12661         if(sce->ed) {
12662                 Sequence *seq;
12663 
12664                 SEQ_BEGIN(sce->ed, seq) {
12665                         if(seq->scene) expand_doit(fd, mainvar, seq->scene);
12666                         if(seq->scene_camera) expand_doit(fd, mainvar, seq->scene_camera);
12667                         if(seq->sound) expand_doit(fd, mainvar, seq->sound);
12668                 }
12669                 SEQ_END
12670         }
12671 
12672 #ifdef DURIAN_CAMERA_SWITCH
12673         {
12674                 TimeMarker *marker;
12675 
12676                 for(marker= sce->markers.first; marker; marker= marker->next) {
12677                         if(marker->camera) {
12678                                 expand_doit(fd, mainvar, marker->camera);
12679                         }
12680                 }
12681         }
12682 #endif
12683 }
12684 
12685 static void expand_camera(FileData *fd, Main *mainvar, Camera *ca)
12686 {
12687         expand_doit(fd, mainvar, ca->ipo); // XXX depreceated - old animation system
12688         
12689         if(ca->adt)
12690                 expand_animdata(fd, mainvar, ca->adt);
12691 }
12692 
12693 static void expand_sound(FileData *fd, Main *mainvar, bSound *snd)
12694 {
12695         expand_doit(fd, mainvar, snd->ipo); // XXX depreceated - old animation system
12696 }
12697 
12698 
12699 static void expand_main(FileData *fd, Main *mainvar)
12700 {
12701         ListBase *lbarray[MAX_LIBARRAY];
12702         ID *id;
12703         int a, doit= 1;
12704 
12705         if(fd==NULL) return;
12706 
12707         while(doit) {
12708                 doit= 0;
12709 
12710                 a= set_listbasepointers(mainvar, lbarray);
12711                 while(a--) {
12712                         id= lbarray[a]->first;
12713 
12714                         while(id) {
12715                                 if(id->flag & LIB_TEST) {
12716 
12717                                         switch(GS(id->name)) {
12718 
12719                                         case ID_OB:
12720                                                 expand_object(fd, mainvar, (Object *)id);
12721                                                 break;
12722                                         case ID_ME:
12723                                                 expand_mesh(fd, mainvar, (Mesh *)id);
12724                                                 break;
12725                                         case ID_CU:
12726                                                 expand_curve(fd, mainvar, (Curve *)id);
12727                                                 break;
12728                                         case ID_MB:
12729                                                 expand_mball(fd, mainvar, (MetaBall *)id);
12730                                                 break;
12731                                         case ID_SCE:
12732                                                 expand_scene(fd, mainvar, (Scene *)id);
12733                                                 break;
12734                                         case ID_MA:
12735                                                 expand_material(fd, mainvar, (Material *)id);
12736                                                 break;
12737                                         case ID_TE:
12738                                                 expand_texture(fd, mainvar, (Tex *)id);
12739                                                 break;
12740                                         case ID_WO:
12741                                                 expand_world(fd, mainvar, (World *)id);
12742                                                 break;
12743                                         case ID_LT:
12744                                                 expand_lattice(fd, mainvar, (Lattice *)id);
12745                                                 break;
12746                                         case ID_LA:
12747                                                 expand_lamp(fd, mainvar,(Lamp *)id);
12748                                                 break;
12749                                         case ID_KE:
12750                                                 expand_key(fd, mainvar, (Key *)id);
12751                                                 break;
12752                                         case ID_CA:
12753                                                 expand_camera(fd, mainvar, (Camera *)id);
12754                                                 break;
12755                                         case ID_SO:
12756                                                 expand_sound(fd, mainvar, (bSound *)id);
12757                                                 break;
12758                                         case ID_AR:
12759                                                 expand_armature(fd, mainvar, (bArmature *)id);
12760                                                 break;
12761                                         case ID_AC:
12762                                                 expand_action(fd, mainvar, (bAction *)id); // XXX depreceated - old animation system
12763                                                 break;
12764                                         case ID_GR:
12765                                                 expand_group(fd, mainvar, (Group *)id);
12766                                                 break;
12767                                         case ID_NT:
12768                                                 expand_nodetree(fd, mainvar, (bNodeTree *)id);
12769                                                 break;
12770                                         case ID_BR:
12771                                                 expand_brush(fd, mainvar, (Brush *)id);
12772                                                 break;
12773                                         case ID_IP:
12774                                                 expand_ipo(fd, mainvar, (Ipo *)id); // XXX depreceated - old animation system
12775                                                 break;
12776                                         case ID_PA:
12777                                                 expand_particlesettings(fd, mainvar, (ParticleSettings *)id);
12778                                         }
12779 
12780                                         doit= 1;
12781                                         id->flag -= LIB_TEST;
12782 
12783                                 }
12784                                 id= id->next;
12785                         }
12786                 }
12787         }
12788 }
12789 
12790 static int object_in_any_scene(Main *mainvar, Object *ob)
12791 {
12792         Scene *sce;
12793         
12794         for(sce= mainvar->scene.first; sce; sce= sce->id.next)
12795                 if(object_in_scene(ob, sce))
12796                         return 1;
12797         return 0;
12798 }
12799 
12800 static void give_base_to_objects(Main *mainvar, Scene *sce, Library *lib, const short idcode, const short is_link)
12801 {
12802         Object *ob;
12803         Base *base;
12804         const short is_group_append= (is_link==FALSE && idcode==ID_GR);
12805 
12806         /* give all objects which are LIB_INDIRECT a base, or for a group when *lib has been set */
12807         for(ob= mainvar->object.first; ob; ob= ob->id.next) {
12808                 
12809                 if( ob->id.flag & LIB_INDIRECT ) {
12810                         
12811                                 /* IF below is quite confusing!
12812                                 if we are appending, but this object wasnt just added allong with a group,
12813                                 then this is already used indirectly in the scene somewhere else and we didnt just append it.
12814                                 
12815                                 (ob->id.flag & LIB_PRE_EXISTING)==0 means that this is a newly appended object - Campbell */
12816                         if (is_group_append==0 || (ob->id.flag & LIB_PRE_EXISTING)==0) {
12817                                 
12818                                 int do_it= 0;
12819                                 
12820                                 if(ob->id.us==0) {
12821                                         do_it= 1;
12822                                 }
12823                                 else if(idcode==ID_GR) {
12824                                         if(ob->id.us==1 && is_link==FALSE && ob->id.lib==lib) {
12825                                                 if((ob->flag & OB_FROMGROUP) && object_in_any_scene(mainvar, ob)==0) {
12826                                                         do_it= 1;
12827                                                 }
12828                                         }
12829                                 }
12830                                 else {
12831                                         /* when appending, make sure any indirectly loaded objects
12832                                          * get a base else they cant be accessed at all [#27437] */
12833                                         if(ob->id.us==1 && is_link==FALSE && ob->id.lib==lib) {
12834 
12835                                                 /* we may be appending from a scene where we already
12836                                                  *  have a linked object which is not in any scene [#27616] */
12837                                                 if((ob->id.flag & LIB_PRE_EXISTING)==0) {
12838 
12839                                                         if(object_in_any_scene(mainvar, ob)==0) {
12840                                                                 do_it= 1;
12841                                                         }
12842                                                 }
12843                                         }
12844                                 }
12845 
12846                                 if(do_it) {
12847                                         base= MEM_callocN( sizeof(Base), "add_ext_base");
12848                                         BLI_addtail(&(sce->base), base);
12849                                         base->lay= ob->lay;
12850                                         base->object= ob;
12851                                         base->flag= ob->flag;
12852                                         ob->id.us= 1;
12853                                         
12854                                         ob->id.flag -= LIB_INDIRECT;
12855                                         ob->id.flag |= LIB_EXTERN;
12856                                 }
12857                         }
12858                 }
12859         }
12860 }
12861 
12862 static void give_base_to_groups(Main *mainvar, Scene *scene)
12863 {
12864         Group *group;
12865 
12866         /* give all objects which are LIB_INDIRECT a base, or for a group when *lib has been set */
12867         for(group= mainvar->group.first; group; group= group->id.next) {
12868                 if(((group->id.flag & LIB_INDIRECT)==0 && (group->id.flag & LIB_PRE_EXISTING)==0)) {
12869                         Base *base;
12870 
12871                         /* add_object(...) messes with the selection */
12872                         Object *ob= add_only_object(OB_EMPTY, group->id.name+2);
12873                         ob->type= OB_EMPTY;
12874                         ob->lay= scene->lay;
12875 
12876                         /* assign the base */
12877                         base= scene_add_base(scene, ob);
12878                         base->flag |= SELECT;
12879                         base->object->flag= base->flag;
12880                         ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
12881                         scene->basact= base;
12882 
12883                         /* assign the group */
12884                         ob->dup_group= group;
12885                         ob->transflag |= OB_DUPLIGROUP;
12886                         rename_id(&ob->id, group->id.name+2);
12887                         VECCOPY(ob->loc, scene->cursor);
12888                 }
12889         }
12890 }
12891 
12892 /* returns true if the item was found
12893 * but it may already have already been appended/linked */
12894 static ID *append_named_part(Main *mainl, FileData *fd, const char *idname, const short idcode)
12895 {
12896         BHead *bhead;
12897         ID *id= NULL;
12898         int found=0;
12899 
12900         for(bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
12901                 if(bhead->code==idcode) {
12902                         const char *idname_test= bhead_id_name(fd, bhead);
12903 
12904                         if(strcmp(idname_test + 2, idname)==0) {
12905                                 found= 1;
12906                                 id= is_yet_read(fd, mainl, bhead);
12907                                 if(id==NULL) {
12908                                         read_libblock(fd, mainl, bhead, LIB_TESTEXT, &id);
12909                                 }
12910                                 else {
12911                                         printf("append: already linked\n");
12912                                         oldnewmap_insert(fd->libmap, bhead->old, id, 1);
12913                                         if(id->flag & LIB_INDIRECT) {
12914                                                 id->flag -= LIB_INDIRECT;
12915                                                 id->flag |= LIB_EXTERN;
12916                                         }
12917                                 }
12918 
12919                                 break;
12920                         }
12921                 }
12922                 else if(bhead->code==ENDB) {
12923                         break;
12924                 }
12925         }
12926 
12927         /* if we found the id but the id is NULL, this is really bad */
12928         BLI_assert((found != 0) == (id != NULL));
12929 
12930         return found ? id : NULL;
12931 }
12932 
12933 static ID *append_named_part_ex(const bContext *C, Main *mainl, FileData *fd, const char *idname, const int idcode, const int flag)
12934 {
12935         ID *id= append_named_part(mainl, fd, idname, idcode);
12936 
12937         if(id && (GS(id->name) == ID_OB)) {     /* loose object: give a base */
12938                 Scene *scene= CTX_data_scene(C); /* can be NULL */
12939                 if(scene) {
12940                         Base *base;
12941                         Object *ob;
12942 
12943                         base= MEM_callocN( sizeof(Base), "app_nam_part");
12944                         BLI_addtail(&scene->base, base);
12945 
12946                         ob= (Object *)id;
12947 
12948                         /* link at active layer (view3d->lay if in context, else scene->lay */
12949                         if((flag & FILE_ACTIVELAY)) {
12950                                 View3D *v3d = CTX_wm_view3d(C);
12951                                 ob->lay = v3d ? v3d->layact : scene->lay;
12952                         }
12953 
12954                         ob->mode= 0;
12955                         base->lay= ob->lay;
12956                         base->object= ob;
12957                         ob->id.us++;
12958 
12959                         if(flag & FILE_AUTOSELECT) {
12960                                 base->flag |= SELECT;
12961                                 base->object->flag = base->flag;
12962                                 /* do NOT make base active here! screws up GUI stuff, if you want it do it on src/ level */
12963                         }
12964                 }
12965         }
12966 
12967         return id;
12968 }
12969 
12970 ID *BLO_library_append_named_part(Main *mainl, BlendHandle** bh, const char *idname, const int idcode)
12971 {
12972         FileData *fd= (FileData*)(*bh);
12973         return append_named_part(mainl, fd, idname, idcode);
12974 }
12975 
12976 ID *BLO_library_append_named_part_ex(const bContext *C, Main *mainl, BlendHandle** bh, const char *idname, const int idcode, const short flag)
12977 {
12978         FileData *fd= (FileData*)(*bh);
12979         return append_named_part_ex(C, mainl, fd, idname, idcode, flag);
12980 }
12981 
12982 static void append_id_part(FileData *fd, Main *mainvar, ID *id, ID **id_r)
12983 {
12984         BHead *bhead;
12985 
12986         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
12987                 if (bhead->code == GS(id->name)) {
12988 
12989                         if (strcmp(id->name, bhead_id_name(fd, bhead))==0) {
12990                                 id->flag &= ~LIB_READ;
12991                                 id->flag |= LIB_TEST;
12992 //                              printf("read lib block %s\n", id->name);
12993                                 read_libblock(fd, mainvar, bhead, id->flag, id_r);
12994 
12995                                 break;
12996                         }
12997                 } else if (bhead->code==ENDB)
12998                         break;
12999         }
13000 }
13001 
13002 /* common routine to append/link something from a library */
13003 
13004 static Main* library_append_begin(Main *mainvar, FileData **fd, const char *filepath)
13005 {
13006         Main *mainl;
13007 
13008         /* make mains */
13009         blo_split_main(&(*fd)->mainlist, mainvar);
13010 
13011         /* which one do we need? */
13012         mainl = blo_find_main(*fd, &(*fd)->mainlist, filepath, G.main->name);
13013         
13014         /* needed for do_version */
13015         mainl->versionfile= (*fd)->fileversion;
13016         read_file_version(*fd, mainl);
13017         
13018         return mainl;
13019 }
13020 
13021 Main* BLO_library_append_begin(Main *mainvar, BlendHandle** bh, const char *filepath)
13022 {
13023         FileData *fd= (FileData*)(*bh);
13024         return library_append_begin(mainvar, &fd, filepath);
13025 }
13026 
13027 
13028 /* Context == NULL signifies not to do any scene manipulation */
13029 static void library_append_end(const bContext *C, Main *mainl, FileData **fd, int idcode, short flag)
13030 {
13031         Main *mainvar;
13032         Library *curlib;
13033 
13034         /* make main consistent */
13035         expand_main(*fd, mainl);
13036 
13037         /* do this when expand found other libs */
13038         read_libraries(*fd, &(*fd)->mainlist);
13039         
13040         curlib= mainl->curlib;
13041 
13042         /* make the lib path relative if required */
13043         if(flag & FILE_RELPATH) {
13044 
13045                 /* use the full path, this could have been read by other library even */
13046                 BLI_strncpy(curlib->name, curlib->filepath, sizeof(curlib->name));
13047                 
13048                 /* uses current .blend file as reference */
13049                 BLI_path_rel(curlib->name, G.main->name);
13050         }
13051 
13052         blo_join_main(&(*fd)->mainlist);
13053         mainvar= (*fd)->mainlist.first;
13054         mainl= NULL; /* blo_join_main free's mainl, cant use anymore */
13055 
13056         lib_link_all(*fd, mainvar);
13057         lib_verify_nodetree(mainvar, FALSE);
13058         fix_relpaths_library(G.main->name, mainvar); /* make all relative paths, relative to the open blend file */
13059 
13060         if(C) {
13061                 Scene *scene= CTX_data_scene(C);
13062 
13063                 /* give a base to loose objects. If group append, do it for objects too */
13064                 if(scene) {
13065                         const short is_link= (flag & FILE_LINK) != 0;
13066                         if(idcode==ID_SCE) {
13067                                 /* dont instance anything when linking in scenes, assume the scene its self instances the data */
13068                         }
13069                         else {
13070                                 give_base_to_objects(mainvar, scene, curlib, idcode, is_link);
13071 
13072                                 if (flag & FILE_GROUP_INSTANCE) {
13073                                         give_base_to_groups(mainvar, scene);
13074                                 }
13075                         }
13076                 }
13077                 else {
13078                         printf("library_append_end, scene is NULL (objects wont get bases)\n");
13079                 }
13080         }
13081         /* has been removed... erm, why? s..ton) */
13082         /* 20040907: looks like they are give base already in append_named_part(); -Nathan L */
13083         /* 20041208: put back. It only linked direct, not indirect objects (ton) */
13084         
13085         /* patch to prevent switch_endian happens twice */
13086         if((*fd)->flags & FD_FLAGS_SWITCH_ENDIAN) {
13087                 blo_freefiledata( *fd );
13088                 *fd = NULL;
13089         }       
13090 }
13091 
13092 void BLO_library_append_end(const bContext *C, struct Main *mainl, BlendHandle** bh, int idcode, short flag)
13093 {
13094         FileData *fd= (FileData*)(*bh);
13095         library_append_end(C, mainl, &fd, idcode, flag);
13096         *bh= (BlendHandle*)fd;
13097 }
13098 
13099 void *BLO_library_read_struct(FileData *fd, BHead *bh, const char *blockname)
13100 {
13101         return read_struct(fd, bh, blockname);
13102 }
13103 
13104 /* ************* READ LIBRARY ************** */
13105 
13106 static int mainvar_count_libread_blocks(Main *mainvar)
13107 {
13108         ListBase *lbarray[MAX_LIBARRAY];
13109         int a, tot= 0;
13110 
13111         a= set_listbasepointers(mainvar, lbarray);
13112         while(a--) {
13113                 ID *id;
13114 
13115                 for (id= lbarray[a]->first; id; id= id->next)
13116                         if (id->flag & LIB_READ)
13117                                 tot++;
13118         }
13119         return tot;
13120 }
13121 
13122 static void read_libraries(FileData *basefd, ListBase *mainlist)
13123 {
13124         Main *mainl= mainlist->first;
13125         Main *mainptr;
13126         ListBase *lbarray[MAX_LIBARRAY];
13127         int a, doit= 1;
13128 
13129         while(doit) {
13130                 doit= 0;
13131 
13132                 /* test 1: read libdata */
13133                 mainptr= mainl->next;
13134                 while(mainptr) {
13135                         int tot= mainvar_count_libread_blocks(mainptr);
13136                         
13137                         // printf("found LIB_READ %s\n", mainptr->curlib->name);
13138                         if(tot) {
13139                                 FileData *fd= mainptr->curlib->filedata;
13140 
13141                                 if(fd==NULL) {
13142 
13143                                         /* printf and reports for now... its important users know this */
13144                                         BKE_reportf(basefd->reports, RPT_INFO, "read library:  '%s', '%s'\n", mainptr->curlib->filepath, mainptr->curlib->name);
13145                                         if(!G.background && basefd->reports) printf("read library: '%s', '%s'\n", mainptr->curlib->filepath, mainptr->curlib->name);
13146 
13147                                         fd= blo_openblenderfile(mainptr->curlib->filepath, basefd->reports);
13148                                         
13149                                         /* allow typing in a new lib path */
13150                                         if(G.rt==-666) {
13151                                                 while(fd==NULL) {
13152                                                         char newlib_path[240] = { 0 };
13153                                                         printf("Missing library...'\n");
13154                                                         printf("        current file: %s\n", G.main->name);
13155                                                         printf("        absolute lib: %s\n", mainptr->curlib->filepath);
13156                                                         printf("        relative lib: %s\n", mainptr->curlib->name);
13157                                                         printf("  enter a new path:\n");
13158 
13159                                                         if(scanf("%s", newlib_path) > 0) {
13160                                                                 strcpy(mainptr->curlib->name, newlib_path);
13161                                                                 strcpy(mainptr->curlib->filepath, newlib_path);
13162                                                                 cleanup_path(G.main->name, mainptr->curlib->filepath);
13163                                                                 
13164                                                                 fd= blo_openblenderfile(mainptr->curlib->filepath, basefd->reports);
13165 
13166                                                                 if(fd) {
13167                                                                         printf("found: '%s', party on macuno!\n", mainptr->curlib->filepath);
13168                                                                 }
13169                                                         }
13170                                                 }
13171                                         }
13172 
13173                                         if (fd) {
13174                                                 fd->reports= basefd->reports;
13175                                                 
13176                                                 if (fd->libmap)
13177                                                         oldnewmap_free(fd->libmap);
13178 
13179                                                 fd->libmap = oldnewmap_new();
13180                                                 
13181                                                 mainptr->curlib->filedata= fd;
13182                                                 mainptr->versionfile= fd->fileversion;
13183                                                 
13184                                                 /* subversion */
13185                                                 read_file_version(fd, mainptr);
13186                                         }
13187                                         else mainptr->curlib->filedata= NULL;
13188 
13189                                         if (fd==NULL) {
13190                                                 BKE_reportf(basefd->reports, RPT_ERROR, "Can't find lib '%s'\n", mainptr->curlib->filepath);
13191                                                 if(!G.background && basefd->reports) printf("ERROR: can't find lib %s \n", mainptr->curlib->filepath);
13192                                         }
13193                                 }
13194                                 if(fd) {
13195                                         doit= 1;
13196                                         a= set_listbasepointers(mainptr, lbarray);
13197                                         while(a--) {
13198                                                 ID *id= lbarray[a]->first;
13199 
13200                                                 while(id) {
13201                                                         ID *idn= id->next;
13202                                                         if(id->flag & LIB_READ) {
13203                                                                 ID *realid= NULL;
13204                                                                 BLI_remlink(lbarray[a], id);
13205 
13206                                                                 append_id_part(fd, mainptr, id, &realid);
13207                                                                 if (!realid) {
13208                                                                         BKE_reportf(fd->reports, RPT_ERROR, "LIB ERROR: %s:'%s' missing from '%s'\n", BKE_idcode_to_name(GS(id->name)), id->name+2, mainptr->curlib->filepath);
13209                                                                         if(!G.background && basefd->reports) printf("LIB ERROR: %s:'%s' missing from '%s'\n", BKE_idcode_to_name(GS(id->name)), id->name+2, mainptr->curlib->filepath);
13210                                                                 }
13211                                                                 
13212                                                                 change_idid_adr(mainlist, basefd, id, realid);
13213 
13214                                                                 MEM_freeN(id);
13215                                                         }
13216                                                         id= idn;
13217                                                 }
13218                                         }
13219 
13220                                         expand_main(fd, mainptr);
13221                                         
13222                                         /* dang FileData... now new libraries need to be appended to original filedata, it is not a good replacement for the old global (ton) */
13223                                         while( fd->mainlist.first ) {
13224                                                 Main *mp= fd->mainlist.first;
13225                                                 BLI_remlink(&fd->mainlist, mp);
13226                                                 BLI_addtail(&basefd->mainlist, mp);
13227                                         }
13228                                 }
13229                         }
13230 
13231                         mainptr= mainptr->next;
13232                 }
13233         }
13234         
13235         /* test if there are unread libblocks */
13236         for(mainptr= mainl->next; mainptr; mainptr= mainptr->next) {
13237                 a= set_listbasepointers(mainptr, lbarray);
13238                 while(a--) {
13239                         ID *id= lbarray[a]->first;
13240                         while(id) {
13241                                 ID *idn= id->next;
13242                                 if(id->flag & LIB_READ) {
13243                                         BLI_remlink(lbarray[a], id);
13244                                         BKE_reportf(basefd->reports, RPT_ERROR, "LIB ERROR: %s:'%s' unread libblock missing from '%s'\n", BKE_idcode_to_name(GS(id->name)), id->name+2, mainptr->curlib->filepath);
13245                                         if(!G.background && basefd->reports)printf("LIB ERROR: %s:'%s' unread libblock missing from '%s'\n", BKE_idcode_to_name(GS(id->name)), id->name+2, mainptr->curlib->filepath);
13246                                         change_idid_adr(mainlist, basefd, id, NULL);
13247 
13248                                         MEM_freeN(id);
13249                                 }
13250                                 id= idn;
13251                         }
13252                 }
13253         }
13254         
13255         /* do versions, link, and free */
13256         for(mainptr= mainl->next; mainptr; mainptr= mainptr->next) {
13257                 /* some mains still have to be read, then
13258                  * versionfile is still zero! */
13259                 if(mainptr->versionfile) {
13260                         if(mainptr->curlib->filedata) // can be zero... with shift+f1 append
13261                                 do_versions(mainptr->curlib->filedata, mainptr->curlib, mainptr);
13262                         else
13263                                 do_versions(basefd, NULL, mainptr);
13264                 }
13265                 
13266                 if(mainptr->curlib->filedata)
13267                         lib_link_all(mainptr->curlib->filedata, mainptr);
13268                 
13269                 if(mainptr->curlib->filedata) blo_freefiledata(mainptr->curlib->filedata);
13270                 mainptr->curlib->filedata= NULL;
13271         }
13272 }
13273 
13274 
13275 /* reading runtime */
13276 
13277 BlendFileData *blo_read_blendafterruntime(int file, char *name, int actualsize, ReportList *reports)
13278 {
13279         BlendFileData *bfd = NULL;
13280         FileData *fd = filedata_new();
13281         fd->filedes = file;
13282         fd->buffersize = actualsize;
13283         fd->read = fd_read_from_file;
13284 
13285         /* needed for library_append and read_libraries */
13286         BLI_strncpy(fd->relabase, name, sizeof(fd->relabase));
13287 
13288         fd = blo_decode_and_check(fd, reports);
13289         if (!fd)
13290                 return NULL;
13291 
13292         fd->reports= reports;
13293         bfd= blo_read_file_internal(fd, "");
13294         blo_freefiledata(fd);
13295 
13296         return bfd;
13297 }