Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  *
26  */
27
28 /** \file blender/blenloader/intern/readfile.c
29  *  \ingroup blenloader
30  */
31
32
33 #include "zlib.h"
34
35 #include <limits.h>
36 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
37 #include <stdlib.h> // for getenv atoi
38 #include <stddef.h> // for offsetof
39 #include <fcntl.h> // for open
40 #include <string.h> // for strrchr strncmp strstr
41 #include <math.h> // for fabs
42 #include <stdarg.h> /* for va_start/end */
43 #include <time.h> /* for gmtime */
44
45 #include "BLI_utildefines.h"
46 #ifndef WIN32
47 #  include <unistd.h> // for read close
48 #else
49 #  include <io.h> // for open close read
50 #  include "winsock2.h"
51 #  include "BLI_winstuff.h"
52 #endif
53
54 /* allow readfile to use deprecated functionality */
55 #define DNA_DEPRECATED_ALLOW
56
57 #include "DNA_anim_types.h"
58 #include "DNA_armature_types.h"
59 #include "DNA_actuator_types.h"
60 #include "DNA_brush_types.h"
61 #include "DNA_camera_types.h"
62 #include "DNA_cachefile_types.h"
63 #include "DNA_cloth_types.h"
64 #include "DNA_controller_types.h"
65 #include "DNA_constraint_types.h"
66 #include "DNA_dynamicpaint_types.h"
67 #include "DNA_effect_types.h"
68 #include "DNA_fileglobal_types.h"
69 #include "DNA_genfile.h"
70 #include "DNA_group_types.h"
71 #include "DNA_gpencil_types.h"
72 #include "DNA_ipo_types.h"
73 #include "DNA_key_types.h"
74 #include "DNA_lattice_types.h"
75 #include "DNA_lamp_types.h"
76 #include "DNA_linestyle_types.h"
77 #include "DNA_meta_types.h"
78 #include "DNA_material_types.h"
79 #include "DNA_mesh_types.h"
80 #include "DNA_meshdata_types.h"
81 #include "DNA_nla_types.h"
82 #include "DNA_node_types.h"
83 #include "DNA_object_fluidsim.h" // NT
84 #include "DNA_object_force.h"
85 #include "DNA_object_types.h"
86 #include "DNA_packedFile_types.h"
87 #include "DNA_property_types.h"
88 #include "DNA_rigidbody_types.h"
89 #include "DNA_text_types.h"
90 #include "DNA_view3d_types.h"
91 #include "DNA_screen_types.h"
92 #include "DNA_sensor_types.h"
93 #include "DNA_sdna_types.h"
94 #include "DNA_scene_types.h"
95 #include "DNA_sequence_types.h"
96 #include "DNA_smoke_types.h"
97 #include "DNA_speaker_types.h"
98 #include "DNA_sound_types.h"
99 #include "DNA_space_types.h"
100 #include "DNA_vfont_types.h"
101 #include "DNA_world_types.h"
102 #include "DNA_movieclip_types.h"
103 #include "DNA_mask_types.h"
104
105 #include "MEM_guardedalloc.h"
106
107 #include "BLI_endian_switch.h"
108 #include "BLI_blenlib.h"
109 #include "BLI_math.h"
110 #include "BLI_threads.h"
111 #include "BLI_mempool.h"
112
113 #include "BLT_translation.h"
114
115 #include "BKE_action.h"
116 #include "BKE_armature.h"
117 #include "BKE_brush.h"
118 #include "BKE_cachefile.h"
119 #include "BKE_cloth.h"
120 #include "BKE_constraint.h"
121 #include "BKE_context.h"
122 #include "BKE_curve.h"
123 #include "BKE_depsgraph.h"
124 #include "BKE_effect.h"
125 #include "BKE_fcurve.h"
126 #include "BKE_global.h" // for G
127 #include "BKE_group.h"
128 #include "BKE_library.h" // for which_libbase
129 #include "BKE_library_idmap.h"
130 #include "BKE_library_query.h"
131 #include "BKE_idcode.h"
132 #include "BKE_material.h"
133 #include "BKE_main.h" // for Main
134 #include "BKE_mesh.h" // for ME_ defines (patching)
135 #include "BKE_modifier.h"
136 #include "BKE_multires.h"
137 #include "BKE_node.h" // for tree type defines
138 #include "BKE_object.h"
139 #include "BKE_paint.h"
140 #include "BKE_report.h"
141 #include "BKE_sca.h" // for init_actuator
142 #include "BKE_scene.h"
143 #include "BKE_screen.h"
144 #include "BKE_sequencer.h"
145 #include "BKE_outliner_treehash.h"
146 #include "BKE_sound.h"
147 #include "BKE_colortools.h"
148
149 #include "NOD_common.h"
150 #include "NOD_socket.h"
151
152 #include "BLO_readfile.h"
153 #include "BLO_undofile.h"
154 #include "BLO_blend_defs.h"
155
156 #include "RE_engine.h"
157
158 #include "readfile.h"
159
160
161 #include <errno.h>
162
163 /**
164  * READ
165  * ====
166  *
167  * - Existing Library (#Main) push or free
168  * - allocate new #Main
169  * - load file
170  * - read #SDNA
171  * - for each LibBlock
172  *   - read LibBlock
173  *   - if a Library
174  *     - make a new #Main
175  *     - attach ID's to it
176  *   - else
177  *     - read associated 'direct data'
178  *     - link direct data (internal and to LibBlock)
179  * - read #FileGlobal
180  * - read #USER data, only when indicated (file is ``~/X.XX/startup.blend``)
181  * - free file
182  * - per Library (per #Main)
183  *   - read file
184  *   - read #SDNA
185  *   - find LibBlocks and attach #ID's to #Main
186  *     - if external LibBlock
187  *       - search all #Main's
188  *         - or it's already read,
189  *         - or not read yet
190  *         - or make new #Main
191  *   - per LibBlock
192  *     - read recursive
193  *     - read associated direct data
194  *     - link direct data (internal and to LibBlock)
195  *   - free file
196  * - per Library with unread LibBlocks
197  *   - read file
198  *   - read #SDNA
199  *   - per LibBlock
200  *     - read recursive
201  *     - read associated direct data
202  *     - link direct data (internal and to LibBlock)
203  *   - free file
204  * - join all #Main's
205  * - link all LibBlocks and indirect pointers to libblocks
206  * - initialize #FileGlobal and copy pointers to #Global
207  *
208  * \note Still a weak point is the new-address function, that doesnt solve reading from
209  * multiple files at the same time.
210  * (added remark: oh, i thought that was solved? will look at that... (ton).
211  */
212
213 /* use GHash for BHead name-based lookups (speeds up linking) */
214 #define USE_GHASH_BHEAD
215
216 /* Use GHash for restoring pointers by name */
217 #define USE_GHASH_RESTORE_POINTER
218
219 /***/
220
221 typedef struct OldNew {
222         const void *old;
223         void *newp;
224         int nr;
225 } OldNew;
226
227 typedef struct OldNewMap {
228         OldNew *entries;
229         int nentries, entriessize;
230         bool sorted;
231         int lasthit;
232 } OldNewMap;
233
234
235 /* local prototypes */
236 static void *read_struct(FileData *fd, BHead *bh, const char *blockname);
237 static void direct_link_modifiers(FileData *fd, ListBase *lb);
238 static void convert_tface_mt(FileData *fd, Main *main);
239 static BHead *find_bhead_from_code_name(FileData *fd, const short idcode, const char *name);
240 static BHead *find_bhead_from_idname(FileData *fd, const char *idname);
241
242 /* this function ensures that reports are printed,
243  * in the case of libraray linking errors this is important!
244  *
245  * bit kludge but better then doubling up on prints,
246  * we could alternatively have a versions of a report function which forces printing - campbell
247  */
248
249 void blo_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
250 {
251         char fixed_buf[1024]; /* should be long enough */
252         
253         va_list args;
254         
255         va_start(args, format);
256         vsnprintf(fixed_buf, sizeof(fixed_buf), format, args);
257         va_end(args);
258         
259         fixed_buf[sizeof(fixed_buf) - 1] = '\0';
260         
261         BKE_report(reports, type, fixed_buf);
262         
263         if (G.background == 0) {
264                 printf("%s: %s\n", BKE_report_type_str(type), fixed_buf);
265         }
266 }
267
268 /* for reporting linking messages */
269 static const char *library_parent_filepath(Library *lib)
270 {
271         return lib->parent ? lib->parent->filepath : "<direct>";
272 }
273
274 static OldNewMap *oldnewmap_new(void) 
275 {
276         OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
277         
278         onm->entriessize = 1024;
279         onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
280         
281         return onm;
282 }
283
284 static int verg_oldnewmap(const void *v1, const void *v2)
285 {
286         const struct OldNew *x1=v1, *x2=v2;
287         
288         if (x1->old > x2->old) return 1;
289         else if (x1->old < x2->old) return -1;
290         return 0;
291 }
292
293
294 static void oldnewmap_sort(FileData *fd) 
295 {
296         BLI_assert(fd->libmap->sorted == false);
297         qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap);
298         fd->libmap->sorted = 1;
299 }
300
301 /* nr is zero for data, and ID code for libdata */
302 static void oldnewmap_insert(OldNewMap *onm, const void *oldaddr, void *newaddr, int nr)
303 {
304         OldNew *entry;
305         
306         if (oldaddr==NULL || newaddr==NULL) return;
307         
308         if (UNLIKELY(onm->nentries == onm->entriessize)) {
309                 onm->entriessize *= 2;
310                 onm->entries = MEM_reallocN(onm->entries, sizeof(*onm->entries) * onm->entriessize);
311         }
312
313         entry = &onm->entries[onm->nentries++];
314         entry->old = oldaddr;
315         entry->newp = newaddr;
316         entry->nr = nr;
317 }
318
319 void blo_do_versions_oldnewmap_insert(OldNewMap *onm, const void *oldaddr, void *newaddr, int nr)
320 {
321         oldnewmap_insert(onm, oldaddr, newaddr, nr);
322 }
323
324 /**
325  * Do a full search (no state).
326  *
327  * \param lasthit: Use as a reference position to avoid a full search
328  * from either end of the array, giving more efficient lookups.
329  *
330  * \note This would seem an ideal case for hash or btree lookups.
331  * However the data is written in-order, using the \a lasthit will normally avoid calling this function.
332  * Creating a btree/hash structure adds overhead for the common-case to optimize the corner-case
333  * (since most entries will never be retrieved).
334  * So just keep full lookups as a fall-back.
335  */
336 static int oldnewmap_lookup_entry_full(const OldNewMap *onm, const void *addr, int lasthit)
337 {
338         const int nentries = onm->nentries;
339         const OldNew *entries = onm->entries;
340         int i;
341
342         /* search relative to lasthit where possible */
343         if (lasthit >= 0 && lasthit < nentries) {
344
345                 /* search forwards */
346                 i = lasthit;
347                 while (++i != nentries) {
348                         if (entries[i].old == addr) {
349                                 return i;
350                         }
351                 }
352
353                 /* search backwards */
354                 i = lasthit + 1;
355                 while (i--) {
356                         if (entries[i].old == addr) {
357                                 return i;
358                         }
359                 }
360         }
361         else {
362                 /* search backwards (full) */
363                 i = nentries;
364                 while (i--) {
365                         if (entries[i].old == addr) {
366                                 return i;
367                         }
368                 }
369         }
370
371         return -1;
372 }
373
374 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, const void *addr, bool increase_users)
375 {
376         int i;
377         
378         if (addr == NULL) return NULL;
379         
380         if (onm->lasthit < onm->nentries-1) {
381                 OldNew *entry = &onm->entries[++onm->lasthit];
382                 
383                 if (entry->old == addr) {
384                         if (increase_users)
385                                 entry->nr++;
386                         return entry->newp;
387                 }
388         }
389         
390         i = oldnewmap_lookup_entry_full(onm, addr, onm->lasthit);
391         if (i != -1) {
392                 OldNew *entry = &onm->entries[i];
393                 BLI_assert(entry->old == addr);
394                 onm->lasthit = i;
395                 if (increase_users)
396                         entry->nr++;
397                 return entry->newp;
398         }
399         
400         return NULL;
401 }
402
403 /* for libdata, nr has ID code, no increment */
404 static void *oldnewmap_liblookup(OldNewMap *onm, const void *addr, const void *lib)
405 {
406         if (addr == NULL) {
407                 return NULL;
408         }
409
410         /* lasthit works fine for non-libdata, linking there is done in same sequence as writing */
411         if (onm->sorted) {
412                 const OldNew entry_s = {.old = addr};
413                 OldNew *entry = bsearch(&entry_s, onm->entries, onm->nentries, sizeof(OldNew), verg_oldnewmap);
414                 if (entry) {
415                         ID *id = entry->newp;
416
417                         if (id && (!lib || id->lib)) {
418                                 return id;
419                         }
420                 }
421         }
422         else {
423                 /* note, this can be a bottle neck when loading some files */
424                 const int i = oldnewmap_lookup_entry_full(onm, addr, -1);
425                 if (i != -1) {
426                         OldNew *entry = &onm->entries[i];
427                         ID *id = entry->newp;
428                         BLI_assert(entry->old == addr);
429                         if (id && (!lib || id->lib)) {
430                                 return id;
431                         }
432                 }
433         }
434
435         return NULL;
436 }
437
438 static void oldnewmap_free_unused(OldNewMap *onm) 
439 {
440         int i;
441
442         for (i = 0; i < onm->nentries; i++) {
443                 OldNew *entry = &onm->entries[i];
444                 if (entry->nr == 0) {
445                         MEM_freeN(entry->newp);
446                         entry->newp = NULL;
447                 }
448         }
449 }
450
451 static void oldnewmap_clear(OldNewMap *onm) 
452 {
453         onm->nentries = 0;
454         onm->lasthit = 0;
455 }
456
457 static void oldnewmap_free(OldNewMap *onm) 
458 {
459         MEM_freeN(onm->entries);
460         MEM_freeN(onm);
461 }
462
463 /***/
464
465 static void read_libraries(FileData *basefd, ListBase *mainlist);
466
467 /* ************ help functions ***************** */
468
469 static void add_main_to_main(Main *mainvar, Main *from)
470 {
471         ListBase *lbarray[MAX_LIBARRAY], *fromarray[MAX_LIBARRAY];
472         int a;
473         
474         set_listbasepointers(mainvar, lbarray);
475         a = set_listbasepointers(from, fromarray);
476         while (a--) {
477                 BLI_movelisttolist(lbarray[a], fromarray[a]);
478         }
479 }
480
481 void blo_join_main(ListBase *mainlist)
482 {
483         Main *tojoin, *mainl;
484         
485         mainl = mainlist->first;
486         while ((tojoin = mainl->next)) {
487                 add_main_to_main(mainl, tojoin);
488                 BLI_remlink(mainlist, tojoin);
489                 BKE_main_free(tojoin);
490         }
491 }
492
493 static void split_libdata(ListBase *lb_src, Main **lib_main_array, const unsigned int lib_main_array_len)
494 {
495         for (ID *id = lb_src->first, *idnext; id; id = idnext) {
496                 idnext = id->next;
497
498                 if (id->lib) {
499                         if (((unsigned int)id->lib->temp_index < lib_main_array_len) &&
500                             /* this check should never fail, just incase 'id->lib' is a dangling pointer. */
501                             (lib_main_array[id->lib->temp_index]->curlib == id->lib))
502                         {
503                                 Main *mainvar = lib_main_array[id->lib->temp_index];
504                                 ListBase *lb_dst = which_libbase(mainvar, GS(id->name));
505                                 BLI_remlink(lb_src, id);
506                                 BLI_addtail(lb_dst, id);
507                         }
508                         else {
509                                 printf("%s: invalid library for '%s'\n", __func__, id->name);
510                                 BLI_assert(0);
511                         }
512                 }
513         }
514 }
515
516 void blo_split_main(ListBase *mainlist, Main *main)
517 {
518         mainlist->first = mainlist->last = main;
519         main->next = NULL;
520         
521         if (BLI_listbase_is_empty(&main->library))
522                 return;
523         
524         /* (Library.temp_index -> Main), lookup table */
525         const unsigned int lib_main_array_len = BLI_listbase_count(&main->library);
526         Main             **lib_main_array     = MEM_mallocN(lib_main_array_len * sizeof(*lib_main_array), __func__);
527
528         int i = 0;
529         for (Library *lib = main->library.first; lib; lib = lib->id.next, i++) {
530                 Main *libmain = BKE_main_new();
531                 libmain->curlib = lib;
532                 BLI_addtail(mainlist, libmain);
533                 lib->temp_index = i;
534                 lib_main_array[i] = libmain;
535         }
536         
537         ListBase *lbarray[MAX_LIBARRAY];
538         i = set_listbasepointers(main, lbarray);
539         while (i--) {
540                 split_libdata(lbarray[i], lib_main_array, lib_main_array_len);
541         }
542
543         MEM_freeN(lib_main_array);
544 }
545
546 static void read_file_version(FileData *fd, Main *main)
547 {
548         BHead *bhead;
549         
550         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
551                 if (bhead->code == GLOB) {
552                         FileGlobal *fg= read_struct(fd, bhead, "Global");
553                         if (fg) {
554                                 main->subversionfile= fg->subversion;
555                                 main->minversionfile= fg->minversion;
556                                 main->minsubversionfile= fg->minsubversion;
557                                 MEM_freeN(fg);
558                         }
559                         else if (bhead->code == ENDB)
560                                 break;
561                 }
562         }
563 }
564
565 #ifdef USE_GHASH_BHEAD
566 static void read_file_bhead_idname_map_create(FileData *fd)
567 {
568         BHead *bhead;
569
570         /* dummy values */
571         bool is_link = false;
572         int code_prev = ENDB;
573         unsigned int reserve = 0;
574
575         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
576                 if (code_prev != bhead->code) {
577                         code_prev = bhead->code;
578                         is_link = BKE_idcode_is_valid(code_prev) ? BKE_idcode_is_linkable(code_prev) : false;
579                 }
580
581                 if (is_link) {
582                         reserve += 1;
583                 }
584         }
585
586         BLI_assert(fd->bhead_idname_hash == NULL);
587
588         fd->bhead_idname_hash = BLI_ghash_str_new_ex(__func__, reserve);
589
590         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
591                 if (code_prev != bhead->code) {
592                         code_prev = bhead->code;
593                         is_link = BKE_idcode_is_valid(code_prev) ? BKE_idcode_is_linkable(code_prev) : false;
594                 }
595
596                 if (is_link) {
597                         BLI_ghash_insert(fd->bhead_idname_hash, (void *)bhead_id_name(fd, bhead), bhead);
598                 }
599         }
600 }
601 #endif
602
603
604 static Main *blo_find_main(FileData *fd, const char *filepath, const char *relabase)
605 {
606         ListBase *mainlist = fd->mainlist;
607         Main *m;
608         Library *lib;
609         char name1[FILE_MAX];
610         
611         BLI_strncpy(name1, filepath, sizeof(name1));
612         BLI_cleanup_path(relabase, name1);
613         
614 //      printf("blo_find_main: relabase  %s\n", relabase);
615 //      printf("blo_find_main: original in  %s\n", filepath);
616 //      printf("blo_find_main: converted to %s\n", name1);
617         
618         for (m = mainlist->first; m; m = m->next) {
619                 const char *libname = (m->curlib) ? m->curlib->filepath : m->name;
620                 
621                 if (BLI_path_cmp(name1, libname) == 0) {
622                         if (G.debug & G_DEBUG) printf("blo_find_main: found library %s\n", libname);
623                         return m;
624                 }
625         }
626         
627         m = BKE_main_new();
628         BLI_addtail(mainlist, m);
629         
630         /* Add library datablock itself to 'main' Main, since libraries are **never** linked data.
631          * Fixes bug where you could end with all ID_LI datablocks having the same name... */
632         lib = BKE_libblock_alloc(mainlist->first, ID_LI, "Lib");
633         lib->id.us = ID_FAKE_USERS(lib);  /* Important, consistency with main ID reading code from read_libblock(). */
634         BLI_strncpy(lib->name, filepath, sizeof(lib->name));
635         BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath));
636         
637         m->curlib = lib;
638         
639         read_file_version(fd, m);
640         
641         if (G.debug & G_DEBUG) printf("blo_find_main: added new lib %s\n", filepath);
642         return m;
643 }
644
645
646 /* ************ FILE PARSING ****************** */
647
648 static void switch_endian_bh4(BHead4 *bhead)
649 {
650         /* the ID_.. codes */
651         if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
652         
653         if (bhead->code != ENDB) {
654                 BLI_endian_switch_int32(&bhead->len);
655                 BLI_endian_switch_int32(&bhead->SDNAnr);
656                 BLI_endian_switch_int32(&bhead->nr);
657         }
658 }
659
660 static void switch_endian_bh8(BHead8 *bhead)
661 {
662         /* the ID_.. codes */
663         if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
664         
665         if (bhead->code != ENDB) {
666                 BLI_endian_switch_int32(&bhead->len);
667                 BLI_endian_switch_int32(&bhead->SDNAnr);
668                 BLI_endian_switch_int32(&bhead->nr);
669         }
670 }
671
672 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
673 {
674         BHead4 *bhead4 = (BHead4 *) bhead;
675         int64_t old;
676
677         bhead4->code = bhead8->code;
678         bhead4->len = bhead8->len;
679
680         if (bhead4->code != ENDB) {
681                 /* perform a endian swap on 64bit pointers, otherwise the pointer might map to zero
682                  * 0x0000000000000000000012345678 would become 0x12345678000000000000000000000000
683                  */
684                 if (do_endian_swap) {
685                         BLI_endian_switch_int64(&bhead8->old);
686                 }
687                 
688                 /* this patch is to avoid a long long being read from not-eight aligned positions
689                  * is necessary on any modern 64bit architecture) */
690                 memcpy(&old, &bhead8->old, 8);
691                 bhead4->old = (int) (old >> 3);
692                 
693                 bhead4->SDNAnr = bhead8->SDNAnr;
694                 bhead4->nr = bhead8->nr;
695         }
696 }
697
698 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
699 {
700         BHead8 *bhead8 = (BHead8 *) bhead;
701         
702         bhead8->code = bhead4->code;
703         bhead8->len = bhead4->len;
704         
705         if (bhead8->code != ENDB) {
706                 bhead8->old = bhead4->old;
707                 bhead8->SDNAnr = bhead4->SDNAnr;
708                 bhead8->nr= bhead4->nr;
709         }
710 }
711
712 static BHeadN *get_bhead(FileData *fd)
713 {
714         BHeadN *new_bhead = NULL;
715         int readsize;
716         
717         if (fd) {
718                 if (!fd->eof) {
719                         /* initializing to zero isn't strictly needed but shuts valgrind up
720                          * since uninitialized memory gets compared */
721                         BHead8 bhead8 = {0};
722                         BHead4 bhead4 = {0};
723                         BHead  bhead = {0};
724                         
725                         /* First read the bhead structure.
726                          * Depending on the platform the file was written on this can
727                          * be a big or little endian BHead4 or BHead8 structure.
728                          *
729                          * As usual 'ENDB' (the last *partial* bhead of the file)
730                          * needs some special handling. We don't want to EOF just yet.
731                          */
732                         if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
733                                 bhead4.code = DATA;
734                                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
735                                 
736                                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
737                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
738                                                 switch_endian_bh4(&bhead4);
739                                         }
740                                         
741                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
742                                                 bh8_from_bh4(&bhead, &bhead4);
743                                         }
744                                         else {
745                                                 memcpy(&bhead, &bhead4, sizeof(bhead));
746                                         }
747                                 }
748                                 else {
749                                         fd->eof = 1;
750                                         bhead.len= 0;
751                                 }
752                         }
753                         else {
754                                 bhead8.code = DATA;
755                                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
756                                 
757                                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
758                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
759                                                 switch_endian_bh8(&bhead8);
760                                         }
761                                         
762                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
763                                                 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
764                                         }
765                                         else {
766                                                 memcpy(&bhead, &bhead8, sizeof(bhead));
767                                         }
768                                 }
769                                 else {
770                                         fd->eof = 1;
771                                         bhead.len= 0;
772                                 }
773                         }
774                         
775                         /* make sure people are not trying to pass bad blend files */
776                         if (bhead.len < 0) fd->eof = 1;
777                         
778                         /* bhead now contains the (converted) bhead structure. Now read
779                          * the associated data and put everything in a BHeadN (creative naming !)
780                          */
781                         if (!fd->eof) {
782                                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
783                                 if (new_bhead) {
784                                         new_bhead->next = new_bhead->prev = NULL;
785                                         new_bhead->bhead = bhead;
786                                         
787                                         readsize = fd->read(fd, new_bhead + 1, bhead.len);
788                                         
789                                         if (readsize != bhead.len) {
790                                                 fd->eof = 1;
791                                                 MEM_freeN(new_bhead);
792                                                 new_bhead = NULL;
793                                         }
794                                 }
795                                 else {
796                                         fd->eof = 1;
797                                 }
798                         }
799                 }
800         }
801
802         /* We've read a new block. Now add it to the list
803          * of blocks.
804          */
805         if (new_bhead) {
806                 BLI_addtail(&fd->listbase, new_bhead);
807         }
808         
809         return(new_bhead);
810 }
811
812 BHead *blo_firstbhead(FileData *fd)
813 {
814         BHeadN *new_bhead;
815         BHead *bhead = NULL;
816         
817         /* Rewind the file
818          * Read in a new block if necessary
819          */
820         new_bhead = fd->listbase.first;
821         if (new_bhead == NULL) {
822                 new_bhead = get_bhead(fd);
823         }
824         
825         if (new_bhead) {
826                 bhead = &new_bhead->bhead;
827         }
828         
829         return(bhead);
830 }
831
832 BHead *blo_prevbhead(FileData *UNUSED(fd), BHead *thisblock)
833 {
834         BHeadN *bheadn = (BHeadN *)POINTER_OFFSET(thisblock, -offsetof(BHeadN, bhead));
835         BHeadN *prev = bheadn->prev;
836         
837         return (prev) ? &prev->bhead : NULL;
838 }
839
840 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
841 {
842         BHeadN *new_bhead = NULL;
843         BHead *bhead = NULL;
844         
845         if (thisblock) {
846                 /* bhead is actually a sub part of BHeadN
847                  * We calculate the BHeadN pointer from the BHead pointer below */
848                 new_bhead = (BHeadN *)POINTER_OFFSET(thisblock, -offsetof(BHeadN, bhead));
849                 
850                 /* get the next BHeadN. If it doesn't exist we read in the next one */
851                 new_bhead = new_bhead->next;
852                 if (new_bhead == NULL) {
853                         new_bhead = get_bhead(fd);
854                 }
855         }
856         
857         if (new_bhead) {
858                 /* here we do the reverse:
859                  * go from the BHeadN pointer to the BHead pointer */
860                 bhead = &new_bhead->bhead;
861         }
862         
863         return(bhead);
864 }
865
866 /* Warning! Caller's responsability to ensure given bhead **is** and ID one! */
867 const char *bhead_id_name(const FileData *fd, const BHead *bhead)
868 {
869         return (const char *)POINTER_OFFSET(bhead, sizeof(*bhead) + fd->id_name_offs);
870 }
871
872 static void decode_blender_header(FileData *fd)
873 {
874         char header[SIZEOFBLENDERHEADER], num[4];
875         int readsize;
876         
877         /* read in the header data */
878         readsize = fd->read(fd, header, sizeof(header));
879         
880         if (readsize == sizeof(header)) {
881                 if (STREQLEN(header, "BLENDER", 7)) {
882                         fd->flags |= FD_FLAGS_FILE_OK;
883                         
884                         /* what size are pointers in the file ? */
885                         if (header[7]=='_') {
886                                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
887                                 if (sizeof(void *) != 4) {
888                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
889                                 }
890                         }
891                         else {
892                                 if (sizeof(void *) != 8) {
893                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
894                                 }
895                         }
896                         
897                         /* is the file saved in a different endian
898                          * than we need ?
899                          */
900                         if (((header[8] == 'v') ? L_ENDIAN : B_ENDIAN) != ENDIAN_ORDER) {
901                                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
902                         }
903                         
904                         /* get the version number */
905                         memcpy(num, header + 9, 3);
906                         num[3] = 0;
907                         fd->fileversion = atoi(num);
908                 }
909         }
910 }
911
912 /**
913  * \return Success if the file is read correctly, else set \a r_error_message.
914  */
915 static bool read_file_dna(FileData *fd, const char **r_error_message)
916 {
917         BHead *bhead;
918         
919         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
920                 if (bhead->code == DNA1) {
921                         const bool do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) != 0;
922                         
923                         fd->filesdna = DNA_sdna_from_data(&bhead[1], bhead->len, do_endian_swap, true, r_error_message);
924                         if (fd->filesdna) {
925                                 fd->compflags = DNA_struct_get_compareflags(fd->filesdna, fd->memsdna);
926                                 /* used to retrieve ID names from (bhead+1) */
927                                 fd->id_name_offs = DNA_elem_offset(fd->filesdna, "ID", "char", "name[]");
928
929                                 return true;
930                         }
931                         else {
932                                 return false;
933                         }
934                         
935                 }
936                 else if (bhead->code == ENDB)
937                         break;
938         }
939         
940         *r_error_message = "Missing DNA block";
941         return false;
942 }
943
944 static int *read_file_thumbnail(FileData *fd)
945 {
946         BHead *bhead;
947         int *blend_thumb = NULL;
948
949         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
950                 if (bhead->code == TEST) {
951                         const bool do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) != 0;
952                         int *data = (int *)(bhead + 1);
953
954                         if (bhead->len < (2 * sizeof(int))) {
955                                 break;
956                         }
957
958                         if (do_endian_swap) {
959                                 BLI_endian_switch_int32(&data[0]);
960                                 BLI_endian_switch_int32(&data[1]);
961                         }
962
963                         if (bhead->len < BLEN_THUMB_MEMSIZE_FILE(data[0], data[1])) {
964                                 break;
965                         }
966
967                         blend_thumb = data;
968                         break;
969                 }
970                 else if (bhead->code != REND) {
971                         /* Thumbnail is stored in TEST immediately after first REND... */
972                         break;
973                 }
974         }
975
976         return blend_thumb;
977 }
978
979 static int fd_read_from_file(FileData *filedata, void *buffer, unsigned int size)
980 {
981         int readsize = read(filedata->filedes, buffer, size);
982         
983         if (readsize < 0) {
984                 readsize = EOF;
985         }
986         else {
987                 filedata->seek += readsize;
988         }
989         
990         return readsize;
991 }
992
993 static int fd_read_gzip_from_file(FileData *filedata, void *buffer, unsigned int size)
994 {
995         int readsize = gzread(filedata->gzfiledes, buffer, size);
996         
997         if (readsize < 0) {
998                 readsize = EOF;
999         }
1000         else {
1001                 filedata->seek += readsize;
1002         }
1003         
1004         return (readsize);
1005 }
1006
1007 static int fd_read_from_memory(FileData *filedata, void *buffer, unsigned int size)
1008 {
1009         /* don't read more bytes then there are available in the buffer */
1010         int readsize = (int)MIN2(size, (unsigned int)(filedata->buffersize - filedata->seek));
1011         
1012         memcpy(buffer, filedata->buffer + filedata->seek, readsize);
1013         filedata->seek += readsize;
1014         
1015         return (readsize);
1016 }
1017
1018 static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int size)
1019 {
1020         static unsigned int seek = (1<<30);     /* the current position */
1021         static unsigned int offset = 0;         /* size of previous chunks */
1022         static MemFileChunk *chunk = NULL;
1023         unsigned int chunkoffset, readsize, totread;
1024         
1025         if (size == 0) return 0;
1026         
1027         if (seek != (unsigned int)filedata->seek) {
1028                 chunk = filedata->memfile->chunks.first;
1029                 seek = 0;
1030                 
1031                 while (chunk) {
1032                         if (seek + chunk->size > (unsigned) filedata->seek) break;
1033                         seek += chunk->size;
1034                         chunk = chunk->next;
1035                 }
1036                 offset = seek;
1037                 seek = filedata->seek;
1038         }
1039         
1040         if (chunk) {
1041                 totread = 0;
1042                 
1043                 do {
1044                         /* first check if it's on the end if current chunk */
1045                         if (seek-offset == chunk->size) {
1046                                 offset += chunk->size;
1047                                 chunk = chunk->next;
1048                         }
1049                         
1050                         /* debug, should never happen */
1051                         if (chunk == NULL) {
1052                                 printf("illegal read, chunk zero\n");
1053                                 return 0;
1054                         }
1055                         
1056                         chunkoffset = seek-offset;
1057                         readsize = size-totread;
1058                         
1059                         /* data can be spread over multiple chunks, so clamp size
1060                          * to within this chunk, and then it will read further in
1061                          * the next chunk */
1062                         if (chunkoffset+readsize > chunk->size)
1063                                 readsize= chunk->size-chunkoffset;
1064                         
1065                         memcpy(POINTER_OFFSET(buffer, totread), chunk->buf + chunkoffset, readsize);
1066                         totread += readsize;
1067                         filedata->seek += readsize;
1068                         seek += readsize;
1069                 } while (totread < size);
1070                 
1071                 return totread;
1072         }
1073         
1074         return 0;
1075 }
1076
1077 static FileData *filedata_new(void)
1078 {
1079         FileData *fd = MEM_callocN(sizeof(FileData), "FileData");
1080         
1081         fd->filedes = -1;
1082         fd->gzfiledes = NULL;
1083
1084         fd->memsdna = DNA_sdna_current_get();
1085
1086         fd->datamap = oldnewmap_new();
1087         fd->globmap = oldnewmap_new();
1088         fd->libmap = oldnewmap_new();
1089         
1090         return fd;
1091 }
1092
1093 static FileData *blo_decode_and_check(FileData *fd, ReportList *reports)
1094 {
1095         decode_blender_header(fd);
1096         
1097         if (fd->flags & FD_FLAGS_FILE_OK) {
1098                 const char *error_message = NULL;
1099                 if (read_file_dna(fd, &error_message) == false) {
1100                         BKE_reportf(reports, RPT_ERROR,
1101                                     "Failed to read blend file '%s': %s",
1102                                     fd->relabase, error_message);
1103                         blo_freefiledata(fd);
1104                         fd = NULL;
1105                 }
1106         }
1107         else {
1108                 BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', not a blend file", fd->relabase);
1109                 blo_freefiledata(fd);
1110                 fd = NULL;
1111         }
1112         
1113         return fd;
1114 }
1115
1116 /* cannot be called with relative paths anymore! */
1117 /* on each new library added, it now checks for the current FileData and expands relativeness */
1118 FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
1119 {
1120         gzFile gzfile;
1121         errno = 0;
1122         gzfile = BLI_gzopen(filepath, "rb");
1123         
1124         if (gzfile == (gzFile)Z_NULL) {
1125                 BKE_reportf(reports, RPT_WARNING, "Unable to open '%s': %s",
1126                             filepath, errno ? strerror(errno) : TIP_("unknown error reading file"));
1127                 return NULL;
1128         }
1129         else {
1130                 FileData *fd = filedata_new();
1131                 fd->gzfiledes = gzfile;
1132                 fd->read = fd_read_gzip_from_file;
1133                 
1134                 /* needed for library_append and read_libraries */
1135                 BLI_strncpy(fd->relabase, filepath, sizeof(fd->relabase));
1136                 
1137                 return blo_decode_and_check(fd, reports);
1138         }
1139 }
1140
1141 /**
1142  * Same as blo_openblenderfile(), but does not reads DNA data, only header. Use it for light access
1143  * (e.g. thumbnail reading).
1144  */
1145 static FileData *blo_openblenderfile_minimal(const char *filepath)
1146 {
1147         gzFile gzfile;
1148         errno = 0;
1149         gzfile = BLI_gzopen(filepath, "rb");
1150
1151         if (gzfile != (gzFile)Z_NULL) {
1152                 FileData *fd = filedata_new();
1153                 fd->gzfiledes = gzfile;
1154                 fd->read = fd_read_gzip_from_file;
1155
1156                 decode_blender_header(fd);
1157
1158                 if (fd->flags & FD_FLAGS_FILE_OK) {
1159                         return fd;
1160                 }
1161
1162                 blo_freefiledata(fd);
1163         }
1164
1165         return NULL;
1166 }
1167
1168 static int fd_read_gzip_from_memory(FileData *filedata, void *buffer, unsigned int size)
1169 {
1170         int err;
1171
1172         filedata->strm.next_out = (Bytef *) buffer;
1173         filedata->strm.avail_out = size;
1174
1175         // Inflate another chunk.
1176         err = inflate (&filedata->strm, Z_SYNC_FLUSH);
1177
1178         if (err == Z_STREAM_END) {
1179                 return 0;
1180         }
1181         else if (err != Z_OK) {
1182                 printf("fd_read_gzip_from_memory: zlib error\n");
1183                 return 0;
1184         }
1185
1186         filedata->seek += size;
1187
1188         return (size);
1189 }
1190
1191 static int fd_read_gzip_from_memory_init(FileData *fd)
1192 {
1193
1194         fd->strm.next_in = (Bytef *) fd->buffer;
1195         fd->strm.avail_in = fd->buffersize;
1196         fd->strm.total_out = 0;
1197         fd->strm.zalloc = Z_NULL;
1198         fd->strm.zfree = Z_NULL;
1199         
1200         if (inflateInit2(&fd->strm, (16+MAX_WBITS)) != Z_OK)
1201                 return 0;
1202
1203         fd->read = fd_read_gzip_from_memory;
1204         
1205         return 1;
1206 }
1207
1208 FileData *blo_openblendermemory(const void *mem, int memsize, ReportList *reports)
1209 {
1210         if (!mem || memsize<SIZEOFBLENDERHEADER) {
1211                 BKE_report(reports, RPT_WARNING, (mem) ? TIP_("Unable to read"): TIP_("Unable to open"));
1212                 return NULL;
1213         }
1214         else {
1215                 FileData *fd = filedata_new();
1216                 const char *cp = mem;
1217                 
1218                 fd->buffer = mem;
1219                 fd->buffersize = memsize;
1220                 
1221                 /* test if gzip */
1222                 if (cp[0] == 0x1f && cp[1] == 0x8b) {
1223                         if (0 == fd_read_gzip_from_memory_init(fd)) {
1224                                 blo_freefiledata(fd);
1225                                 return NULL;
1226                         }
1227                 }
1228                 else
1229                         fd->read = fd_read_from_memory;
1230                         
1231                 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1232
1233                 return blo_decode_and_check(fd, reports);
1234         }
1235 }
1236
1237 FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports)
1238 {
1239         if (!memfile) {
1240                 BKE_report(reports, RPT_WARNING, "Unable to open blend <memory>");
1241                 return NULL;
1242         }
1243         else {
1244                 FileData *fd = filedata_new();
1245                 fd->memfile = memfile;
1246                 
1247                 fd->read = fd_read_from_memfile;
1248                 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1249                 
1250                 return blo_decode_and_check(fd, reports);
1251         }
1252 }
1253
1254
1255 void blo_freefiledata(FileData *fd)
1256 {
1257         if (fd) {
1258                 if (fd->filedes != -1) {
1259                         close(fd->filedes);
1260                 }
1261                 
1262                 if (fd->gzfiledes != NULL) {
1263                         gzclose(fd->gzfiledes);
1264                 }
1265                 
1266                 if (fd->strm.next_in) {
1267                         if (inflateEnd(&fd->strm) != Z_OK) {
1268                                 printf("close gzip stream error\n");
1269                         }
1270                 }
1271                 
1272                 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
1273                         MEM_freeN((void *)fd->buffer);
1274                         fd->buffer = NULL;
1275                 }
1276                 
1277                 // Free all BHeadN data blocks
1278                 BLI_freelistN(&fd->listbase);
1279
1280                 if (fd->filesdna)
1281                         DNA_sdna_free(fd->filesdna);
1282                 if (fd->compflags)
1283                         MEM_freeN((void *)fd->compflags);
1284                 
1285                 if (fd->datamap)
1286                         oldnewmap_free(fd->datamap);
1287                 if (fd->globmap)
1288                         oldnewmap_free(fd->globmap);
1289                 if (fd->imamap)
1290                         oldnewmap_free(fd->imamap);
1291                 if (fd->movieclipmap)
1292                         oldnewmap_free(fd->movieclipmap);
1293                 if (fd->soundmap)
1294                         oldnewmap_free(fd->soundmap);
1295                 if (fd->packedmap)
1296                         oldnewmap_free(fd->packedmap);
1297                 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
1298                         oldnewmap_free(fd->libmap);
1299                 if (fd->bheadmap)
1300                         MEM_freeN(fd->bheadmap);
1301                 
1302 #ifdef USE_GHASH_BHEAD
1303                 if (fd->bhead_idname_hash) {
1304                         BLI_ghash_free(fd->bhead_idname_hash, NULL, NULL);
1305                 }
1306 #endif
1307
1308                 MEM_freeN(fd);
1309         }
1310 }
1311
1312 /* ************ DIV ****************** */
1313
1314 /**
1315  * Check whether given path ends with a blend file compatible extension (.blend, .ble or .blend.gz).
1316  *
1317  * \param str The path to check.
1318  * \return true is this path ends with a blender file extension.
1319  */
1320 bool BLO_has_bfile_extension(const char *str)
1321 {
1322         const char *ext_test[4] = {".blend", ".ble", ".blend.gz", NULL};
1323         return BLI_testextensie_array(str, ext_test);
1324 }
1325
1326 /**
1327  * Try to explode given path into its 'library components' (i.e. a .blend file, id type/group, and datablock itself).
1328  *
1329  * \param path the full path to explode.
1330  * \param r_dir the string that'll contain path up to blend file itself ('library' path).
1331  *              WARNING! Must be FILE_MAX_LIBEXTRA long (it also stores group and name strings)!
1332  * \param r_group the string that'll contain 'group' part of the path, if any. May be NULL.
1333  * \param r_name the string that'll contain data's name part of the path, if any. May be NULL.
1334  * \return true if path contains a blend file.
1335  */
1336 bool BLO_library_path_explode(const char *path, char *r_dir, char **r_group, char **r_name)
1337 {
1338         /* We might get some data names with slashes, so we have to go up in path until we find blend file itself,
1339          * then we now next path item is group, and everything else is data name. */
1340         char *slash = NULL, *prev_slash = NULL, c = '\0';
1341
1342         r_dir[0] = '\0';
1343         if (r_group) {
1344                 *r_group = NULL;
1345         }
1346         if (r_name) {
1347                 *r_name = NULL;
1348         }
1349
1350         /* if path leads to an existing directory, we can be sure we're not (in) a library */
1351         if (BLI_is_dir(path)) {
1352                 return false;
1353         }
1354
1355         strcpy(r_dir, path);
1356
1357         while ((slash = (char *)BLI_last_slash(r_dir))) {
1358                 char tc = *slash;
1359                 *slash = '\0';
1360                 if (BLO_has_bfile_extension(r_dir) && BLI_is_file(r_dir)) {
1361                         break;
1362                 }
1363
1364                 if (prev_slash) {
1365                         *prev_slash = c;
1366                 }
1367                 prev_slash = slash;
1368                 c = tc;
1369         }
1370
1371         if (!slash) {
1372                 return false;
1373         }
1374
1375         if (slash[1] != '\0') {
1376                 BLI_assert(strlen(slash + 1) < BLO_GROUP_MAX);
1377                 if (r_group) {
1378                         *r_group = slash + 1;
1379                 }
1380         }
1381
1382         if (prev_slash && (prev_slash[1] != '\0')) {
1383                 BLI_assert(strlen(prev_slash + 1) < MAX_ID_NAME - 2);
1384                 if (r_name) {
1385                         *r_name = prev_slash + 1;
1386                 }
1387         }
1388
1389         return true;
1390 }
1391
1392 /**
1393  * Does a very light reading of given .blend file to extract its stored thumbnail.
1394  *
1395  * \param filepath The path of the file to extract thumbnail from.
1396  * \return The raw thumbnail
1397  *         (MEM-allocated, as stored in file, use BKE_main_thumbnail_to_imbuf() to convert it to ImBuf image).
1398  */
1399 BlendThumbnail *BLO_thumbnail_from_file(const char *filepath)
1400 {
1401         FileData *fd;
1402         BlendThumbnail *data;
1403         int *fd_data;
1404
1405         fd = blo_openblenderfile_minimal(filepath);
1406         fd_data = fd ? read_file_thumbnail(fd) : NULL;
1407
1408         if (fd_data) {
1409                 const size_t sz = BLEN_THUMB_MEMSIZE(fd_data[0], fd_data[1]);
1410                 data = MEM_mallocN(sz, __func__);
1411
1412                 BLI_assert((sz - sizeof(*data)) == (BLEN_THUMB_MEMSIZE_FILE(fd_data[0], fd_data[1]) - (sizeof(*fd_data) * 2)));
1413                 data->width = fd_data[0];
1414                 data->height = fd_data[1];
1415                 memcpy(data->rect, &fd_data[2], sz - sizeof(*data));
1416         }
1417         else {
1418                 data = NULL;
1419         }
1420
1421         blo_freefiledata(fd);
1422
1423         return data;
1424 }
1425
1426 /* ************** OLD POINTERS ******************* */
1427
1428 static void *newdataadr(FileData *fd, const void *adr)          /* only direct databocks */
1429 {
1430         return oldnewmap_lookup_and_inc(fd->datamap, adr, true);
1431 }
1432
1433 /* This is a special version of newdataadr() which allows us to keep lasthit of
1434  * map unchanged. In certain cases this makes file loading time significantly
1435  * faster.
1436  *
1437  * Use this function in cases like restoring pointer from one list element to
1438  * another list element, but keep lasthit value so we can continue restoring
1439  * pointers efficiently.
1440  *
1441  * Example of this could be found in direct_link_fcurves() which restores the
1442  * fcurve group pointer and keeps lasthit optimal for linking all further
1443  * fcurves.
1444  */
1445 static void *newdataadr_ex(FileData *fd, const void *adr, bool increase_lasthit)                /* only direct databocks */
1446 {
1447         if (increase_lasthit) {
1448                 return newdataadr(fd, adr);
1449         }
1450         else {
1451                 int lasthit = fd->datamap->lasthit;
1452                 void *newadr = newdataadr(fd, adr);
1453                 fd->datamap->lasthit = lasthit;
1454                 return newadr;
1455         }
1456 }
1457
1458 static void *newdataadr_no_us(FileData *fd, const void *adr)            /* only direct databocks */
1459 {
1460         return oldnewmap_lookup_and_inc(fd->datamap, adr, false);
1461 }
1462
1463 static void *newglobadr(FileData *fd, const void *adr)      /* direct datablocks with global linking */
1464 {
1465         return oldnewmap_lookup_and_inc(fd->globmap, adr, true);
1466 }
1467
1468 static void *newimaadr(FileData *fd, const void *adr)               /* used to restore image data after undo */
1469 {
1470         if (fd->imamap && adr)
1471                 return oldnewmap_lookup_and_inc(fd->imamap, adr, true);
1472         return NULL;
1473 }
1474
1475 static void *newmclipadr(FileData *fd, const void *adr)      /* used to restore movie clip data after undo */
1476 {
1477         if (fd->movieclipmap && adr)
1478                 return oldnewmap_lookup_and_inc(fd->movieclipmap, adr, true);
1479         return NULL;
1480 }
1481
1482 static void *newsoundadr(FileData *fd, const void *adr)      /* used to restore sound data after undo */
1483 {
1484         if (fd->soundmap && adr)
1485                 return oldnewmap_lookup_and_inc(fd->soundmap, adr, true);
1486         return NULL;
1487 }
1488
1489 static void *newpackedadr(FileData *fd, const void *adr)      /* used to restore packed data after undo */
1490 {
1491         if (fd->packedmap && adr)
1492                 return oldnewmap_lookup_and_inc(fd->packedmap, adr, true);
1493         
1494         return oldnewmap_lookup_and_inc(fd->datamap, adr, true);
1495 }
1496
1497
1498 static void *newlibadr(FileData *fd, const void *lib, const void *adr)          /* only lib data */
1499 {
1500         return oldnewmap_liblookup(fd->libmap, adr, lib);
1501 }
1502
1503 void *blo_do_versions_newlibadr(FileData *fd, const void *lib, const void *adr)         /* only lib data */
1504 {
1505         return newlibadr(fd, lib, adr);
1506 }
1507
1508 static void *newlibadr_us(FileData *fd, const void *lib, const void *adr)       /* increases user number */
1509 {
1510         ID *id = newlibadr(fd, lib, adr);
1511         
1512         id_us_plus_no_lib(id);
1513         
1514         return id;
1515 }
1516
1517 void *blo_do_versions_newlibadr_us(FileData *fd, const void *lib, const void *adr)      /* increases user number */
1518 {
1519         return newlibadr_us(fd, lib, adr);
1520 }
1521
1522 static void *newlibadr_real_us(FileData *fd, const void *lib, const void *adr)  /* ensures real user */
1523 {
1524         ID *id = newlibadr(fd, lib, adr);
1525
1526         id_us_ensure_real(id);
1527
1528         return id;
1529 }
1530
1531 static void change_idid_adr_fd(FileData *fd, const void *old, void *new)
1532 {
1533         int i;
1534         
1535         /* use a binary search if we have a sorted libmap, for now it's not needed. */
1536         BLI_assert(fd->libmap->sorted == false);
1537
1538         for (i = 0; i < fd->libmap->nentries; i++) {
1539                 OldNew *entry = &fd->libmap->entries[i];
1540                 
1541                 if (old==entry->newp && entry->nr==ID_ID) {
1542                         entry->newp = new;
1543                         if (new) entry->nr = GS( ((ID *)new)->name );
1544                 }
1545         }
1546 }
1547
1548 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
1549 {
1550         Main *mainptr;
1551         
1552         for (mainptr = mainlist->first; mainptr; mainptr = mainptr->next) {
1553                 FileData *fd;
1554                 
1555                 if (mainptr->curlib)
1556                         fd = mainptr->curlib->filedata;
1557                 else
1558                         fd = basefd;
1559                 
1560                 if (fd) {
1561                         change_idid_adr_fd(fd, old, new);
1562                 }
1563         }
1564 }
1565
1566 /* lib linked proxy objects point to our local data, we need
1567  * to clear that pointer before reading the undo memfile since
1568  * the object might be removed, it is set again in reading
1569  * if the local object still exists */
1570 void blo_clear_proxy_pointers_from_lib(Main *oldmain)
1571 {
1572         Object *ob = oldmain->object.first;
1573         
1574         for (; ob; ob= ob->id.next) {
1575                 if (ob->id.lib)
1576                         ob->proxy_from = NULL;
1577         }
1578 }
1579
1580 void blo_make_image_pointer_map(FileData *fd, Main *oldmain)
1581 {
1582         Image *ima = oldmain->image.first;
1583         Scene *sce = oldmain->scene.first;
1584         int a;
1585         
1586         fd->imamap = oldnewmap_new();
1587         
1588         for (; ima; ima = ima->id.next) {
1589                 if (ima->cache)
1590                         oldnewmap_insert(fd->imamap, ima->cache, ima->cache, 0);
1591                 for (a = 0; a < TEXTARGET_COUNT; a++)
1592                         if (ima->gputexture[a])
1593                                 oldnewmap_insert(fd->imamap, ima->gputexture[a], ima->gputexture[a], 0);
1594                 if (ima->rr)
1595                         oldnewmap_insert(fd->imamap, ima->rr, ima->rr, 0);
1596                 for (a=0; a < IMA_MAX_RENDER_SLOT; a++)
1597                         if (ima->renders[a])
1598                                 oldnewmap_insert(fd->imamap, ima->renders[a], ima->renders[a], 0);
1599         }
1600         for (; sce; sce = sce->id.next) {
1601                 if (sce->nodetree && sce->nodetree->previews) {
1602                         bNodeInstanceHashIterator iter;
1603                         NODE_INSTANCE_HASH_ITER(iter, sce->nodetree->previews) {
1604                                 bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
1605                                 oldnewmap_insert(fd->imamap, preview, preview, 0);
1606                         }
1607                 }
1608         }
1609 }
1610
1611 /* set old main image ibufs to zero if it has been restored */
1612 /* this works because freeing old main only happens after this call */
1613 void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
1614 {
1615         OldNew *entry = fd->imamap->entries;
1616         Image *ima = oldmain->image.first;
1617         Scene *sce = oldmain->scene.first;
1618         int i;
1619         
1620         /* used entries were restored, so we put them to zero */
1621         for (i = 0; i < fd->imamap->nentries; i++, entry++) {
1622                 if (entry->nr > 0)
1623                         entry->newp = NULL;
1624         }
1625         
1626         for (; ima; ima = ima->id.next) {
1627                 ima->cache = newimaadr(fd, ima->cache);
1628                 if (ima->cache == NULL) {
1629                         ima->tpageflag &= ~IMA_GLBIND_IS_DATA;
1630                         for (i = 0; i < TEXTARGET_COUNT; i++) {
1631                                 ima->bindcode[i] = 0;
1632                                 ima->gputexture[i] = NULL;
1633                         }
1634                         ima->rr = NULL;
1635                 }
1636                 for (i = 0; i < IMA_MAX_RENDER_SLOT; i++)
1637                         ima->renders[i] = newimaadr(fd, ima->renders[i]);
1638                 
1639                 for (i = 0; i < TEXTARGET_COUNT; i++)
1640                         ima->gputexture[i] = newimaadr(fd, ima->gputexture[i]);
1641                 ima->rr = newimaadr(fd, ima->rr);
1642         }
1643         for (; sce; sce = sce->id.next) {
1644                 if (sce->nodetree && sce->nodetree->previews) {
1645                         bNodeInstanceHash *new_previews = BKE_node_instance_hash_new("node previews");
1646                         bNodeInstanceHashIterator iter;
1647                         
1648                         /* reconstruct the preview hash, only using remaining pointers */
1649                         NODE_INSTANCE_HASH_ITER(iter, sce->nodetree->previews) {
1650                                 bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
1651                                 if (preview) {
1652                                         bNodePreview *new_preview = newimaadr(fd, preview);
1653                                         if (new_preview) {
1654                                                 bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter);
1655                                                 BKE_node_instance_hash_insert(new_previews, key, new_preview);
1656                                         }
1657                                 }
1658                         }
1659                         BKE_node_instance_hash_free(sce->nodetree->previews, NULL);
1660                         sce->nodetree->previews = new_previews;
1661                 }
1662         }
1663 }
1664
1665 void blo_make_movieclip_pointer_map(FileData *fd, Main *oldmain)
1666 {
1667         MovieClip *clip = oldmain->movieclip.first;
1668         Scene *sce = oldmain->scene.first;
1669         
1670         fd->movieclipmap = oldnewmap_new();
1671         
1672         for (; clip; clip = clip->id.next) {
1673                 if (clip->cache)
1674                         oldnewmap_insert(fd->movieclipmap, clip->cache, clip->cache, 0);
1675                 
1676                 if (clip->tracking.camera.intrinsics)
1677                         oldnewmap_insert(fd->movieclipmap, clip->tracking.camera.intrinsics, clip->tracking.camera.intrinsics, 0);
1678         }
1679         
1680         for (; sce; sce = sce->id.next) {
1681                 if (sce->nodetree) {
1682                         bNode *node;
1683                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1684                                 if (node->type == CMP_NODE_MOVIEDISTORTION)
1685                                         oldnewmap_insert(fd->movieclipmap, node->storage, node->storage, 0);
1686                 }
1687         }
1688 }
1689
1690 /* set old main movie clips caches to zero if it has been restored */
1691 /* this works because freeing old main only happens after this call */
1692 void blo_end_movieclip_pointer_map(FileData *fd, Main *oldmain)
1693 {
1694         OldNew *entry = fd->movieclipmap->entries;
1695         MovieClip *clip = oldmain->movieclip.first;
1696         Scene *sce = oldmain->scene.first;
1697         int i;
1698         
1699         /* used entries were restored, so we put them to zero */
1700         for (i=0; i < fd->movieclipmap->nentries; i++, entry++) {
1701                 if (entry->nr > 0)
1702                         entry->newp = NULL;
1703         }
1704         
1705         for (; clip; clip = clip->id.next) {
1706                 clip->cache = newmclipadr(fd, clip->cache);
1707                 clip->tracking.camera.intrinsics = newmclipadr(fd, clip->tracking.camera.intrinsics);
1708         }
1709         
1710         for (; sce; sce = sce->id.next) {
1711                 if (sce->nodetree) {
1712                         bNode *node;
1713                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1714                                 if (node->type == CMP_NODE_MOVIEDISTORTION)
1715                                         node->storage = newmclipadr(fd, node->storage);
1716                 }
1717         }
1718 }
1719
1720 void blo_make_sound_pointer_map(FileData *fd, Main *oldmain)
1721 {
1722         bSound *sound = oldmain->sound.first;
1723         
1724         fd->soundmap = oldnewmap_new();
1725         
1726         for (; sound; sound = sound->id.next) {
1727                 if (sound->waveform)
1728                         oldnewmap_insert(fd->soundmap, sound->waveform, sound->waveform, 0);                    
1729         }
1730 }
1731
1732 /* set old main sound caches to zero if it has been restored */
1733 /* this works because freeing old main only happens after this call */
1734 void blo_end_sound_pointer_map(FileData *fd, Main *oldmain)
1735 {
1736         OldNew *entry = fd->soundmap->entries;
1737         bSound *sound = oldmain->sound.first;
1738         int i;
1739         
1740         /* used entries were restored, so we put them to zero */
1741         for (i = 0; i < fd->soundmap->nentries; i++, entry++) {
1742                 if (entry->nr > 0)
1743                         entry->newp = NULL;
1744         }
1745         
1746         for (; sound; sound = sound->id.next) {
1747                 sound->waveform = newsoundadr(fd, sound->waveform);
1748         }
1749 }
1750
1751 /* XXX disabled this feature - packed files also belong in temp saves and quit.blend, to make restore work */
1752
1753 static void insert_packedmap(FileData *fd, PackedFile *pf)
1754 {
1755         oldnewmap_insert(fd->packedmap, pf, pf, 0);
1756         oldnewmap_insert(fd->packedmap, pf->data, pf->data, 0);
1757 }
1758
1759 void blo_make_packed_pointer_map(FileData *fd, Main *oldmain)
1760 {
1761         Image *ima;
1762         VFont *vfont;
1763         bSound *sound;
1764         Library *lib;
1765         
1766         fd->packedmap = oldnewmap_new();
1767         
1768         for (ima = oldmain->image.first; ima; ima = ima->id.next) {
1769                 ImagePackedFile *imapf;
1770
1771                 if (ima->packedfile)
1772                         insert_packedmap(fd, ima->packedfile);
1773
1774                 for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next)
1775                         if (imapf->packedfile)
1776                                 insert_packedmap(fd, imapf->packedfile);
1777         }
1778                         
1779         for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next)
1780                 if (vfont->packedfile)
1781                         insert_packedmap(fd, vfont->packedfile);
1782         
1783         for (sound = oldmain->sound.first; sound; sound = sound->id.next)
1784                 if (sound->packedfile)
1785                         insert_packedmap(fd, sound->packedfile);
1786         
1787         for (lib = oldmain->library.first; lib; lib = lib->id.next)
1788                 if (lib->packedfile)
1789                         insert_packedmap(fd, lib->packedfile);
1790
1791 }
1792
1793 /* set old main packed data to zero if it has been restored */
1794 /* this works because freeing old main only happens after this call */
1795 void blo_end_packed_pointer_map(FileData *fd, Main *oldmain)
1796 {
1797         Image *ima;
1798         VFont *vfont;
1799         bSound *sound;
1800         Library *lib;
1801         OldNew *entry = fd->packedmap->entries;
1802         int i;
1803         
1804         /* used entries were restored, so we put them to zero */
1805         for (i=0; i < fd->packedmap->nentries; i++, entry++) {
1806                 if (entry->nr > 0)
1807                         entry->newp = NULL;
1808         }
1809         
1810         for (ima = oldmain->image.first; ima; ima = ima->id.next) {
1811                 ImagePackedFile *imapf;
1812
1813                 ima->packedfile = newpackedadr(fd, ima->packedfile);
1814
1815                 for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next)
1816                         imapf->packedfile = newpackedadr(fd, imapf->packedfile);
1817         }
1818         
1819         for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next)
1820                 vfont->packedfile = newpackedadr(fd, vfont->packedfile);
1821
1822         for (sound = oldmain->sound.first; sound; sound = sound->id.next)
1823                 sound->packedfile = newpackedadr(fd, sound->packedfile);
1824                 
1825         for (lib = oldmain->library.first; lib; lib = lib->id.next)
1826                 lib->packedfile = newpackedadr(fd, lib->packedfile);
1827 }
1828
1829
1830 /* undo file support: add all library pointers in lookup */
1831 void blo_add_library_pointer_map(ListBase *old_mainlist, FileData *fd)
1832 {
1833         Main *ptr = old_mainlist->first;
1834         ListBase *lbarray[MAX_LIBARRAY];
1835         
1836         for (ptr = ptr->next; ptr; ptr = ptr->next) {
1837                 int i = set_listbasepointers(ptr, lbarray);
1838                 while (i--) {
1839                         ID *id;
1840                         for (id = lbarray[i]->first; id; id = id->next)
1841                                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
1842                 }
1843         }
1844
1845         fd->old_mainlist = old_mainlist;
1846 }
1847
1848
1849 /* ********** END OLD POINTERS ****************** */
1850 /* ********** READ FILE ****************** */
1851
1852 static void switch_endian_structs(const struct SDNA *filesdna, BHead *bhead)
1853 {
1854         int blocksize, nblocks;
1855         char *data;
1856         
1857         data = (char *)(bhead+1);
1858         blocksize = filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1859         
1860         nblocks = bhead->nr;
1861         while (nblocks--) {
1862                 DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data);
1863                 
1864                 data += blocksize;
1865         }
1866 }
1867
1868 static void *read_struct(FileData *fd, BHead *bh, const char *blockname)
1869 {
1870         void *temp = NULL;
1871         
1872         if (bh->len) {
1873                 /* switch is based on file dna */
1874                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1875                         switch_endian_structs(fd->filesdna, bh);
1876                 
1877                 if (fd->compflags[bh->SDNAnr] != SDNA_CMP_REMOVED) {
1878                         if (fd->compflags[bh->SDNAnr] == SDNA_CMP_NOT_EQUAL) {
1879                                 temp = DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1880                         }
1881                         else {
1882                                 /* SDNA_CMP_EQUAL */
1883                                 temp = MEM_mallocN(bh->len, blockname);
1884                                 memcpy(temp, (bh+1), bh->len);
1885                         }
1886                 }
1887         }
1888
1889         return temp;
1890 }
1891
1892 typedef void (*link_list_cb)(FileData *fd, void *data);
1893
1894 static void link_list_ex(FileData *fd, ListBase *lb, link_list_cb callback)             /* only direct data */
1895 {
1896         Link *ln, *prev;
1897         
1898         if (BLI_listbase_is_empty(lb)) return;
1899         
1900         lb->first = newdataadr(fd, lb->first);
1901         if (callback != NULL) {
1902                 callback(fd, lb->first);
1903         }
1904         ln = lb->first;
1905         prev = NULL;
1906         while (ln) {
1907                 ln->next = newdataadr(fd, ln->next);
1908                 if (ln->next != NULL && callback != NULL) {
1909                         callback(fd, ln->next);
1910                 }
1911                 ln->prev = prev;
1912                 prev = ln;
1913                 ln = ln->next;
1914         }
1915         lb->last = prev;
1916 }
1917
1918 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1919 {
1920         link_list_ex(fd, lb, NULL);
1921 }
1922
1923 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1924 {
1925         Link *ln, *prev;
1926         void *poin;
1927
1928         if (BLI_listbase_is_empty(lb)) return;
1929         poin = newdataadr(fd, lb->first);
1930         if (lb->first) {
1931                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1932         }
1933         lb->first = poin;
1934         
1935         ln = lb->first;
1936         prev = NULL;
1937         while (ln) {
1938                 poin = newdataadr(fd, ln->next);
1939                 if (ln->next) {
1940                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1941                 }
1942                 ln->next = poin;
1943                 ln->prev = prev;
1944                 prev = ln;
1945                 ln = ln->next;
1946         }
1947         lb->last = prev;
1948 }
1949
1950 static void test_pointer_array(FileData *fd, void **mat)
1951 {
1952         int64_t *lpoin, *lmat;
1953         int *ipoin, *imat;
1954         size_t len;
1955
1956                 /* manually convert the pointer array in
1957                  * the old dna format to a pointer array in
1958                  * the new dna format.
1959                  */
1960         if (*mat) {
1961                 len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1962                         
1963                 if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1964                         ipoin=imat= MEM_mallocN(len * 4, "newmatar");
1965                         lpoin= *mat;
1966                         
1967                         while (len-- > 0) {
1968                                 if ((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1969                                         BLI_endian_switch_int64(lpoin);
1970                                 *ipoin = (int)((*lpoin) >> 3);
1971                                 ipoin++;
1972                                 lpoin++;
1973                         }
1974                         MEM_freeN(*mat);
1975                         *mat = imat;
1976                 }
1977                 
1978                 if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1979                         lpoin = lmat = MEM_mallocN(len * 8, "newmatar");
1980                         ipoin = *mat;
1981                         
1982                         while (len-- > 0) {
1983                                 *lpoin = *ipoin;
1984                                 ipoin++;
1985                                 lpoin++;
1986                         }
1987                         MEM_freeN(*mat);
1988                         *mat= lmat;
1989                 }
1990         }
1991 }
1992
1993 /* ************ READ ID Properties *************** */
1994
1995 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1996 static void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1997
1998 static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
1999 {
2000         IDProperty *array;
2001         int i;
2002         
2003         /* since we didn't save the extra buffer, set totallen to len */
2004         prop->totallen = prop->len;
2005         prop->data.pointer = newdataadr(fd, prop->data.pointer);
2006
2007         array = (IDProperty *)prop->data.pointer;
2008         
2009         /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared
2010          * theres not really anything we can do to correct this, at least don't crash */
2011         if (array == NULL) {
2012                 prop->len = 0;
2013                 prop->totallen = 0;
2014         }
2015         
2016         
2017         for (i = 0; i < prop->len; i++)
2018                 IDP_DirectLinkProperty(&array[i], switch_endian, fd);
2019 }
2020
2021 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
2022 {
2023         IDProperty **array;
2024         int i;
2025         
2026         /* since we didn't save the extra buffer, set totallen to len */
2027         prop->totallen = prop->len;
2028         prop->data.pointer = newdataadr(fd, prop->data.pointer);
2029         
2030         if (prop->subtype == IDP_GROUP) {
2031                 test_pointer_array(fd, prop->data.pointer);
2032                 array = prop->data.pointer;
2033                 
2034                 for (i = 0; i < prop->len; i++)
2035                         IDP_DirectLinkProperty(array[i], switch_endian, fd);
2036         }
2037         else if (prop->subtype == IDP_DOUBLE) {
2038                 if (switch_endian) {
2039                         BLI_endian_switch_double_array(prop->data.pointer, prop->len);
2040                 }
2041         }
2042         else {
2043                 if (switch_endian) {
2044                         /* also used for floats */
2045                         BLI_endian_switch_int32_array(prop->data.pointer, prop->len);
2046                 }
2047         }
2048 }
2049
2050 static void IDP_DirectLinkString(IDProperty *prop, FileData *fd)
2051 {
2052         /*since we didn't save the extra string buffer, set totallen to len.*/
2053         prop->totallen = prop->len;
2054         prop->data.pointer = newdataadr(fd, prop->data.pointer);
2055 }
2056
2057 static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *fd)
2058 {
2059         ListBase *lb = &prop->data.group;
2060         IDProperty *loop;
2061         
2062         link_list(fd, lb);
2063         
2064         /*Link child id properties now*/
2065         for (loop=prop->data.group.first; loop; loop=loop->next) {
2066                 IDP_DirectLinkProperty(loop, switch_endian, fd);
2067         }
2068 }
2069
2070 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
2071 {
2072         switch (prop->type) {
2073                 case IDP_GROUP:
2074                         IDP_DirectLinkGroup(prop, switch_endian, fd);
2075                         break;
2076                 case IDP_STRING:
2077                         IDP_DirectLinkString(prop, fd);
2078                         break;
2079                 case IDP_ARRAY:
2080                         IDP_DirectLinkArray(prop, switch_endian, fd);
2081                         break;
2082                 case IDP_IDPARRAY:
2083                         IDP_DirectLinkIDPArray(prop, switch_endian, fd);
2084                         break;
2085                 case IDP_DOUBLE:
2086                         /* erg, stupid doubles.  since I'm storing them
2087                          * in the same field as int val; val2 in the
2088                          * IDPropertyData struct, they have to deal with
2089                          * endianness specifically
2090                          *
2091                          * in theory, val and val2 would've already been swapped
2092                          * if switch_endian is true, so we have to first unswap
2093                          * them then reswap them as a single 64-bit entity.
2094                          */
2095                         
2096                         if (switch_endian) {
2097                                 BLI_endian_switch_int32(&prop->data.val);
2098                                 BLI_endian_switch_int32(&prop->data.val2);
2099                                 BLI_endian_switch_int64((int64_t *)&prop->data.val);
2100                         }
2101                         
2102                         break;
2103         }
2104 }
2105
2106 #define IDP_DirectLinkGroup_OrFree(prop, switch_endian, fd) \
2107        _IDP_DirectLinkGroup_OrFree(prop, switch_endian, fd, __func__)
2108
2109 static void _IDP_DirectLinkGroup_OrFree(IDProperty **prop, int switch_endian, FileData *fd,
2110                                         const char *caller_func_id)
2111 {
2112         if (*prop) {
2113                 if ((*prop)->type == IDP_GROUP) {
2114                         IDP_DirectLinkGroup(*prop, switch_endian, fd);
2115                 }
2116                 else {
2117                         /* corrupt file! */
2118                         printf("%s: found non group data, freeing type %d!\n",
2119                                caller_func_id, (*prop)->type);
2120                         /* don't risk id, data's likely corrupt. */
2121                         // IDP_FreeProperty(*prop);
2122                         *prop = NULL;
2123                 }
2124         }
2125 }
2126
2127 /* stub function */
2128 static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endian), FileData *UNUSED(fd))
2129 {
2130         /* Should we do something here, prop should be ensured to be non-NULL first... */
2131 }
2132
2133 /* ************ READ IMAGE PREVIEW *************** */
2134
2135 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
2136 {
2137         PreviewImage *prv = newdataadr(fd, old_prv);
2138         
2139         if (prv) {
2140                 int i;
2141                 for (i = 0; i < NUM_ICON_SIZES; ++i) {
2142                         if (prv->rect[i]) {
2143                                 prv->rect[i] = newdataadr(fd, prv->rect[i]);
2144                         }
2145                         prv->gputexture[i] = NULL;
2146                 }
2147                 prv->icon_id = 0;
2148         }
2149         
2150         return prv;
2151 }
2152
2153 /* ************ READ ID *************** */
2154
2155 static void direct_link_id(FileData *fd, ID *id)
2156 {
2157         /*link direct data of ID properties*/
2158         if (id->properties) {
2159                 id->properties = newdataadr(fd, id->properties);
2160                 /* this case means the data was written incorrectly, it should not happen */
2161                 IDP_DirectLinkGroup_OrFree(&id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2162         }
2163 }
2164
2165 /* ************ READ CurveMapping *************** */
2166
2167 /* cuma itself has been read! */
2168 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
2169 {
2170         int a;
2171         
2172         /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
2173         cumap->flag &= ~CUMA_PREMULLED;
2174         
2175         for (a = 0; a < CM_TOT; a++) {
2176                 cumap->cm[a].curve = newdataadr(fd, cumap->cm[a].curve);
2177                 cumap->cm[a].table = NULL;
2178                 cumap->cm[a].premultable = NULL;
2179         }
2180 }
2181
2182 /* ************ READ Brush *************** */
2183 /* library brush linking after fileread */
2184 static void lib_link_brush(FileData *fd, Main *main)
2185 {
2186         Brush *brush;
2187         
2188         /* only link ID pointers */
2189         for (brush = main->brush.first; brush; brush = brush->id.next) {
2190                 if (brush->id.tag & LIB_TAG_NEED_LINK) {
2191                         brush->id.tag &= ~LIB_TAG_NEED_LINK;
2192                         
2193                         /* brush->(mask_)mtex.obj is ignored on purpose? */
2194                         brush->mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mtex.tex);
2195                         brush->mask_mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mask_mtex.tex);
2196                         brush->clone.image = newlibadr(fd, brush->id.lib, brush->clone.image);
2197                         brush->toggle_brush = newlibadr(fd, brush->id.lib, brush->toggle_brush);
2198                         brush->paint_curve = newlibadr_us(fd, brush->id.lib, brush->paint_curve);
2199                 }
2200         }
2201 }
2202
2203 static void direct_link_brush(FileData *fd, Brush *brush)
2204 {
2205         /* brush itself has been read */
2206
2207         /* fallof curve */
2208         brush->curve = newdataadr(fd, brush->curve);
2209         brush->gradient = newdataadr(fd, brush->gradient);
2210
2211         if (brush->curve)
2212                 direct_link_curvemapping(fd, brush->curve);
2213         else
2214                 BKE_brush_curve_preset(brush, CURVE_PRESET_SHARP);
2215
2216         brush->preview = NULL;
2217         brush->icon_imbuf = NULL;
2218 }
2219
2220 /* ************ READ Palette *************** */
2221 static void lib_link_palette(FileData *UNUSED(fd), Main *main)
2222 {
2223         Palette *palette;
2224
2225         /* only link ID pointers */
2226         for (palette = main->palettes.first; palette; palette = palette->id.next) {
2227                 if (palette->id.tag & LIB_TAG_NEED_LINK) {
2228                         palette->id.tag &= ~LIB_TAG_NEED_LINK;
2229                 }
2230         }
2231 }
2232
2233 static void direct_link_palette(FileData *fd, Palette *palette)
2234 {
2235         /* palette itself has been read */
2236         link_list(fd, &palette->colors);
2237 }
2238
2239 static void lib_link_paint_curve(FileData *UNUSED(fd), Main *main)
2240 {
2241         PaintCurve *pc;
2242
2243         /* only link ID pointers */
2244         for (pc = main->paintcurves.first; pc; pc = pc->id.next) {
2245                 if (pc->id.tag & LIB_TAG_NEED_LINK) {
2246                         pc->id.tag &= ~LIB_TAG_NEED_LINK;
2247                 }
2248         }
2249 }
2250
2251 static void direct_link_paint_curve(FileData *fd, PaintCurve *pc)
2252 {
2253         pc->points = newdataadr(fd, pc->points);
2254 }
2255
2256 /* ************ READ PACKEDFILE *************** */
2257
2258 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
2259 {
2260         PackedFile *pf = newpackedadr(fd, oldpf);
2261
2262         if (pf) {
2263                 pf->data = newpackedadr(fd, pf->data);
2264         }
2265         
2266         return pf;
2267 }
2268
2269 /* ************ READ ANIMATION STUFF ***************** */
2270
2271 /* Legacy Data Support (for Version Patching) ----------------------------- */
2272
2273 // XXX deprecated - old animation system
2274 static void lib_link_ipo(FileData *fd, Main *main)
2275 {
2276         Ipo *ipo;
2277         
2278         for (ipo = main->ipo.first; ipo; ipo = ipo->id.next) {
2279                 if (ipo->id.tag & LIB_TAG_NEED_LINK) {
2280                         IpoCurve *icu;
2281                         for (icu = ipo->curve.first; icu; icu = icu->next) {
2282                                 if (icu->driver)
2283                                         icu->driver->ob = newlibadr(fd, ipo->id.lib, icu->driver->ob);
2284                         }
2285                         ipo->id.tag &= ~LIB_TAG_NEED_LINK;
2286                 }
2287         }
2288 }
2289
2290 // XXX deprecated - old animation system
2291 static void direct_link_ipo(FileData *fd, Ipo *ipo)
2292 {
2293         IpoCurve *icu;
2294
2295         link_list(fd, &(ipo->curve));
2296         
2297         for (icu = ipo->curve.first; icu; icu = icu->next) {
2298                 icu->bezt = newdataadr(fd, icu->bezt);
2299                 icu->bp = newdataadr(fd, icu->bp);
2300                 icu->driver = newdataadr(fd, icu->driver);
2301         }
2302 }
2303
2304 // XXX deprecated - old animation system
2305 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
2306 {
2307         bActionStrip *strip;
2308         bActionModifier *amod;
2309         
2310         for (strip=striplist->first; strip; strip=strip->next) {
2311                 strip->object = newlibadr(fd, id->lib, strip->object);
2312                 strip->act = newlibadr_us(fd, id->lib, strip->act);
2313                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
2314                 for (amod = strip->modifiers.first; amod; amod = amod->next)
2315                         amod->ob = newlibadr(fd, id->lib, amod->ob);
2316         }
2317 }
2318
2319 // XXX deprecated - old animation system
2320 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
2321 {
2322         bActionStrip *strip;
2323         
2324         link_list(fd, strips);
2325         
2326         for (strip = strips->first; strip; strip = strip->next)
2327                 link_list(fd, &strip->modifiers);
2328 }
2329
2330 // XXX deprecated - old animation system
2331 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
2332 {
2333         bConstraintChannel *chan;
2334
2335         for (chan=chanbase->first; chan; chan=chan->next) {
2336                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
2337         }
2338 }
2339
2340 /* Data Linking ----------------------------- */
2341
2342 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
2343 {
2344         FModifier *fcm;
2345         
2346         for (fcm = list->first; fcm; fcm = fcm->next) {
2347                 /* data for specific modifiers */
2348                 switch (fcm->type) {
2349                         case FMODIFIER_TYPE_PYTHON:
2350                         {
2351                                 FMod_Python *data = (FMod_Python *)fcm->data;
2352                                 data->script = newlibadr(fd, id->lib, data->script);
2353
2354                                 break;
2355                         }
2356                 }
2357         }
2358 }
2359
2360 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
2361 {
2362         FCurve *fcu;
2363         
2364         if (list == NULL)
2365                 return;
2366         
2367         /* relink ID-block references... */
2368         for (fcu = list->first; fcu; fcu = fcu->next) {
2369                 /* driver data */
2370                 if (fcu->driver) {
2371                         ChannelDriver *driver = fcu->driver;
2372                         DriverVar *dvar;
2373                         
2374                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
2375                                 DRIVER_TARGETS_LOOPER(dvar)
2376                                 {
2377                                         /* only relink if still used */
2378                                         if (tarIndex < dvar->num_targets)
2379                                                 dtar->id = newlibadr(fd, id->lib, dtar->id); 
2380                                         else
2381                                                 dtar->id = NULL;
2382                                 }
2383                                 DRIVER_TARGETS_LOOPER_END
2384                         }
2385                 }
2386                 
2387                 /* modifiers */
2388                 lib_link_fmodifiers(fd, id, &fcu->modifiers);
2389         }
2390 }
2391
2392
2393 /* NOTE: this assumes that link_list has already been called on the list */
2394 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
2395 {
2396         FModifier *fcm;
2397         
2398         for (fcm = list->first; fcm; fcm = fcm->next) {
2399                 /* relink general data */
2400                 fcm->data  = newdataadr(fd, fcm->data);
2401                 
2402                 /* do relinking of data for specific types */
2403                 switch (fcm->type) {
2404                         case FMODIFIER_TYPE_GENERATOR:
2405                         {
2406                                 FMod_Generator *data = (FMod_Generator *)fcm->data;
2407                                 
2408                                 data->coefficients = newdataadr(fd, data->coefficients);
2409                                 
2410                                 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2411                                         BLI_endian_switch_float_array(data->coefficients, data->arraysize);
2412                                 }
2413
2414                                 break;
2415                         }
2416                         case FMODIFIER_TYPE_ENVELOPE:
2417                         {
2418                                 FMod_Envelope *data=  (FMod_Envelope *)fcm->data;
2419                                 
2420                                 data->data= newdataadr(fd, data->data);
2421
2422                                 break;
2423                         }
2424                         case FMODIFIER_TYPE_PYTHON:
2425                         {
2426                                 FMod_Python *data = (FMod_Python *)fcm->data;
2427                                 
2428                                 data->prop = newdataadr(fd, data->prop);
2429                                 IDP_DirectLinkGroup_OrFree(&data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2430
2431                                 break;
2432                         }
2433                 }
2434         }
2435 }
2436
2437 /* NOTE: this assumes that link_list has already been called on the list */
2438 static void direct_link_fcurves(FileData *fd, ListBase *list)
2439 {
2440         FCurve *fcu;
2441         
2442         /* link F-Curve data to F-Curve again (non ID-libs) */
2443         for (fcu = list->first; fcu; fcu = fcu->next) {
2444                 /* curve data */
2445                 fcu->bezt = newdataadr(fd, fcu->bezt);
2446                 fcu->fpt = newdataadr(fd, fcu->fpt);
2447                 
2448                 /* rna path */
2449                 fcu->rna_path = newdataadr(fd, fcu->rna_path);
2450                 
2451                 /* group */
2452                 fcu->grp = newdataadr_ex(fd, fcu->grp, false);
2453                 
2454                 /* clear disabled flag - allows disabled drivers to be tried again ([#32155]),
2455                  * but also means that another method for "reviving disabled F-Curves" exists
2456                  */
2457                 fcu->flag &= ~FCURVE_DISABLED;
2458                 
2459                 /* driver */
2460                 fcu->driver= newdataadr(fd, fcu->driver);
2461                 if (fcu->driver) {
2462                         ChannelDriver *driver= fcu->driver;
2463                         DriverVar *dvar;
2464                         
2465                         /* compiled expression data will need to be regenerated (old pointer may still be set here) */
2466                         driver->expr_comp = NULL;
2467                         
2468                         /* give the driver a fresh chance - the operating environment may be different now 
2469                          * (addons, etc. may be different) so the driver namespace may be sane now [#32155]
2470                          */
2471                         driver->flag &= ~DRIVER_FLAG_INVALID;
2472                         
2473                         /* relink variables, targets and their paths */
2474                         link_list(fd, &driver->variables);
2475                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
2476                                 DRIVER_TARGETS_LOOPER(dvar)
2477                                 {
2478                                         /* only relink the targets being used */
2479                                         if (tarIndex < dvar->num_targets)
2480                                                 dtar->rna_path = newdataadr(fd, dtar->rna_path);
2481                                         else
2482                                                 dtar->rna_path = NULL;
2483                                 }
2484                                 DRIVER_TARGETS_LOOPER_END
2485                         }
2486                 }
2487                 
2488                 /* modifiers */
2489                 link_list(fd, &fcu->modifiers);
2490                 direct_link_fmodifiers(fd, &fcu->modifiers);
2491         }
2492 }
2493
2494
2495 static void lib_link_action(FileData *fd, Main *main)
2496 {
2497         bAction *act;
2498         bActionChannel *chan;
2499
2500         for (act = main->action.first; act; act = act->id.next) {
2501                 if (act->id.tag & LIB_TAG_NEED_LINK) {
2502                         act->id.tag &= ~LIB_TAG_NEED_LINK;
2503                         
2504 // XXX deprecated - old animation system <<<
2505                         for (chan=act->chanbase.first; chan; chan=chan->next) {
2506                                 chan->ipo = newlibadr_us(fd, act->id.lib, chan->ipo);
2507                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
2508                         }
2509 // >>> XXX deprecated - old animation system
2510                         
2511                         lib_link_fcurves(fd, &act->id, &act->curves);
2512                 }
2513         }
2514 }
2515
2516 static void direct_link_action(FileData *fd, bAction *act)
2517 {
2518         bActionChannel *achan; // XXX deprecated - old animation system
2519         bActionGroup *agrp;
2520
2521         link_list(fd, &act->curves);
2522         link_list(fd, &act->chanbase); // XXX deprecated - old animation system
2523         link_list(fd, &act->groups);
2524         link_list(fd, &act->markers);
2525
2526 // XXX deprecated - old animation system <<<
2527         for (achan = act->chanbase.first; achan; achan=achan->next) {
2528                 achan->grp = newdataadr(fd, achan->grp);
2529                 
2530                 link_list(fd, &achan->constraintChannels);
2531         }
2532 // >>> XXX deprecated - old animation system
2533
2534         direct_link_fcurves(fd, &act->curves);
2535         
2536         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
2537                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
2538                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
2539         }
2540 }
2541
2542 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
2543 {
2544         NlaStrip *strip;
2545         
2546         for (strip = list->first; strip; strip = strip->next) {
2547                 /* check strip's children */
2548                 lib_link_nladata_strips(fd, id, &strip->strips);
2549                 
2550                 /* check strip's F-Curves */
2551                 lib_link_fcurves(fd, id, &strip->fcurves);
2552                 
2553                 /* reassign the counted-reference to action */
2554                 strip->act = newlibadr_us(fd, id->lib, strip->act);
2555                 
2556                 /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */
2557                 if ((strip->act) && (strip->act->idroot == 0))
2558                         strip->act->idroot = GS(id->name);
2559         }
2560 }
2561
2562 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
2563 {
2564         NlaTrack *nlt;
2565         
2566         /* we only care about the NLA strips inside the tracks */
2567         for (nlt = list->first; nlt; nlt = nlt->next) {
2568                 lib_link_nladata_strips(fd, id, &nlt->strips);
2569         }
2570 }
2571
2572 /* This handles Animato NLA-Strips linking 
2573  * NOTE: this assumes that link_list has already been called on the list 
2574  */
2575 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
2576 {
2577         NlaStrip *strip;
2578         
2579         for (strip = list->first; strip; strip = strip->next) {
2580                 /* strip's child strips */
2581                 link_list(fd, &strip->strips);
2582                 direct_link_nladata_strips(fd, &strip->strips);
2583                 
2584                 /* strip's F-Curves */
2585                 link_list(fd, &strip->fcurves);
2586                 direct_link_fcurves(fd, &strip->fcurves);
2587                 
2588                 /* strip's F-Modifiers */
2589                 link_list(fd, &strip->modifiers);
2590                 direct_link_fmodifiers(fd, &strip->modifiers);
2591         }
2592 }
2593
2594 /* NOTE: this assumes that link_list has already been called on the list */
2595 static void direct_link_nladata(FileData *fd, ListBase *list)
2596 {
2597         NlaTrack *nlt;
2598         
2599         for (nlt = list->first; nlt; nlt = nlt->next) {
2600                 /* relink list of strips */
2601                 link_list(fd, &nlt->strips);
2602                 
2603                 /* relink strip data */
2604                 direct_link_nladata_strips(fd, &nlt->strips);
2605         }
2606 }
2607
2608 /* ------- */
2609
2610 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
2611 {
2612         KeyingSet *ks;
2613         KS_Path *ksp;
2614         
2615         /* here, we're only interested in the ID pointer stored in some of the paths */
2616         for (ks = list->first; ks; ks = ks->next) {
2617                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2618                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
2619                 }
2620         }
2621 }
2622
2623 /* NOTE: this assumes that link_list has already been called on the list */
2624 static void direct_link_keyingsets(FileData *fd, ListBase *list)
2625 {
2626         KeyingSet *ks;
2627         KS_Path *ksp;
2628         
2629         /* link KeyingSet data to KeyingSet again (non ID-libs) */
2630         for (ks = list->first; ks; ks = ks->next) {
2631                 /* paths */
2632                 link_list(fd, &ks->paths);
2633                 
2634                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2635                         /* rna path */
2636                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
2637                 }
2638         }
2639 }
2640
2641 /* ------- */
2642
2643 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
2644 {
2645         if (adt == NULL)
2646                 return;
2647         
2648         /* link action data */
2649         adt->action= newlibadr_us(fd, id->lib, adt->action);
2650         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
2651         
2652         /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */
2653         if ((adt->action) && (adt->action->idroot == 0))
2654                 adt->action->idroot = GS(id->name);
2655         if ((adt->tmpact) && (adt->tmpact->idroot == 0))
2656                 adt->tmpact->idroot = GS(id->name);
2657         
2658         /* link drivers */
2659         lib_link_fcurves(fd, id, &adt->drivers);
2660         
2661         /* overrides don't have lib-link for now, so no need to do anything */
2662         
2663         /* link NLA-data */
2664         lib_link_nladata(fd, id, &adt->nla_tracks);
2665 }
2666
2667 static void direct_link_animdata(FileData *fd, AnimData *adt)
2668 {
2669         /* NOTE: must have called newdataadr already before doing this... */
2670         if (adt == NULL)
2671                 return;
2672         
2673         /* link drivers */
2674         link_list(fd, &adt->drivers);
2675         direct_link_fcurves(fd, &adt->drivers);
2676         
2677         /* link overrides */
2678         // TODO...
2679         
2680         /* link NLA-data */
2681         link_list(fd, &adt->nla_tracks);
2682         direct_link_nladata(fd, &adt->nla_tracks);
2683         
2684         /* relink active track/strip - even though strictly speaking this should only be used
2685          * if we're in 'tweaking mode', we need to be able to have this loaded back for
2686          * undo, but also since users may not exit tweakmode before saving (#24535)
2687          */
2688         // TODO: it's not really nice that anyone should be able to save the file in this
2689         //              state, but it's going to be too hard to enforce this single case...
2690         adt->act_track = newdataadr(fd, adt->act_track);
2691         adt->actstrip = newdataadr(fd, adt->actstrip);
2692 }       
2693
2694 /* ************ READ CACHEFILES *************** */
2695
2696 static void lib_link_cachefiles(FileData *fd, Main *bmain)
2697 {
2698         CacheFile *cache_file;
2699
2700         /* only link ID pointers */
2701         for (cache_file = bmain->cachefiles.first; cache_file; cache_file = cache_file->id.next) {
2702                 if (cache_file->id.tag & LIB_TAG_NEED_LINK) {
2703                         cache_file->id.tag &= ~LIB_TAG_NEED_LINK;
2704                 }
2705
2706                 BLI_listbase_clear(&cache_file->object_paths);
2707                 cache_file->handle = NULL;
2708
2709                 if (cache_file->adt) {
2710                         lib_link_animdata(fd, &cache_file->id, cache_file->adt);
2711                 }
2712         }
2713 }
2714
2715 static void direct_link_cachefile(FileData *fd, CacheFile *cache_file)
2716 {
2717         cache_file->handle = NULL;
2718
2719         /* relink animdata */
2720         cache_file->adt = newdataadr(fd, cache_file->adt);
2721         direct_link_animdata(fd, cache_file->adt);
2722 }
2723
2724 /* ************ READ MOTION PATHS *************** */
2725
2726 /* direct data for cache */
2727 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
2728 {
2729         /* sanity check */
2730         if (mpath == NULL)
2731                 return;
2732         
2733         /* relink points cache */
2734         mpath->points = newdataadr(fd, mpath->points);
2735 }
2736
2737 /* ************ READ NODE TREE *************** */
2738
2739 static void lib_link_node_socket(FileData *fd, ID *UNUSED(id), bNodeSocket *sock)
2740 {
2741         /* Link ID Properties -- and copy this comment EXACTLY for easy finding
2742          * of library blocks that implement this.*/
2743         IDP_LibLinkProperty(sock->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2744 }
2745
2746 /* Single node tree (also used for material/scene trees), ntree is not NULL */
2747 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
2748 {
2749         bNode *node;
2750         bNodeSocket *sock;
2751         
2752         lib_link_animdata(fd, &ntree->id, ntree->adt);
2753         
2754         ntree->gpd = newlibadr_us(fd, id->lib, ntree->gpd);
2755         
2756         for (node = ntree->nodes.first; node; node = node->next) {
2757                 /* Link ID Properties -- and copy this comment EXACTLY for easy finding
2758                  * of library blocks that implement this.*/
2759                 IDP_LibLinkProperty(node->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2760                 
2761                 node->id= newlibadr_us(fd, id->lib, node->id);
2762
2763                 for (sock = node->inputs.first; sock; sock = sock->next)
2764                         lib_link_node_socket(fd, id, sock);
2765                 for (sock = node->outputs.first; sock; sock = sock->next)
2766                         lib_link_node_socket(fd, id, sock);
2767         }
2768         
2769         for (sock = ntree->inputs.first; sock; sock = sock->next)
2770                 lib_link_node_socket(fd, id, sock);
2771         for (sock = ntree->outputs.first; sock; sock = sock->next)
2772                 lib_link_node_socket(fd, id, sock);
2773 }
2774
2775 /* library ntree linking after fileread */
2776 static void lib_link_nodetree(FileData *fd, Main *main)
2777 {
2778         bNodeTree *ntree;
2779         
2780         /* only link ID pointers */
2781         for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2782                 if (ntree->id.tag & LIB_TAG_NEED_LINK) {
2783                         ntree->id.tag &= ~LIB_TAG_NEED_LINK;
2784                         lib_link_ntree(fd, &ntree->id, ntree);
2785                 }
2786         }
2787 }
2788
2789 /* updates group node socket identifier so that
2790  * external links to/from the group node are preserved.
2791  */
2792 static void lib_node_do_versions_group_indices(bNode *gnode)
2793 {
2794         bNodeTree *ngroup = (bNodeTree*)gnode->id;
2795         bNodeSocket *sock;
2796         bNodeLink *link;
2797         
2798         for (sock=gnode->outputs.first; sock; sock = sock->next) {
2799                 int old_index = sock->to_index;
2800                 
2801                 for (link = ngroup->links.first; link; link = link->next) {
2802                         if (link->tonode == NULL && link->fromsock->own_index == old_index) {
2803                                 strcpy(sock->identifier, link->fromsock->identifier);
2804                                 /* deprecated */
2805                                 sock->own_index = link->fromsock->own_index;
2806                                 sock->to_index = 0;
2807                                 sock->groupsock = NULL;
2808                         }
2809                 }
2810         }
2811         for (sock=gnode->inputs.first; sock; sock = sock->next) {
2812                 int old_index = sock->to_index;
2813                 
2814                 for (link = ngroup->links.first; link; link = link->next) {
2815                         if (link->fromnode == NULL && link->tosock->own_index == old_index) {
2816                                 strcpy(sock->identifier, link->tosock->identifier);
2817                                 /* deprecated */
2818                                 sock->own_index = link->tosock->own_index;
2819                                 sock->to_index = 0;
2820                                 sock->groupsock = NULL;
2821                         }
2822                 }
2823         }
2824 }
2825
2826 /* verify types for nodes and groups, all data has to be read */
2827 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
2828  * typedefs */
2829 static void lib_verify_nodetree(Main *main, int UNUSED(open))
2830 {
2831         /* this crashes blender on undo/redo */
2832 #if 0
2833                 if (open == 1) {
2834                         reinit_nodesystem();
2835                 }
2836 #endif
2837         
2838         /* set node->typeinfo pointers */
2839         FOREACH_NODETREE(main, ntree, id) {
2840                 ntreeSetTypes(NULL, ntree);
2841         } FOREACH_NODETREE_END
2842         
2843         /* verify static socket templates */
2844         FOREACH_NODETREE(main, ntree, id) {
2845                 bNode *node;
2846                 for (node=ntree->nodes.first; node; node=node->next)
2847                         node_verify_socket_templates(ntree, node);
2848         } FOREACH_NODETREE_END
2849         
2850         {
2851                 bool has_old_groups = false;
2852                 /* XXX this should actually be part of do_versions, but since we need
2853                  * finished library linking, it is not possible there. Instead in do_versions
2854                  * we have set the NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2 flag, so at this point we can do the
2855                  * actual group node updates.
2856                  */
2857                 for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2858                         if (ntree->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2) {
2859                                 has_old_groups = 1;
2860                         }
2861                 }
2862                 
2863                 if (has_old_groups) {
2864                         FOREACH_NODETREE(main, ntree, id) {
2865                                 /* updates external links for all group nodes in a tree */
2866                                 bNode *node;
2867                                 for (node = ntree->nodes.first; node; node = node->next) {
2868                                         if (node->type == NODE_GROUP) {
2869                                                 bNodeTree *ngroup = (bNodeTree*)node->id;
2870                                                 if (ngroup && (ngroup->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2))
2871                                                         lib_node_do_versions_group_indices(node);
2872                                         }
2873                                 }
2874                         } FOREACH_NODETREE_END
2875                 }
2876                 
2877                 for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2878                         ntree->flag &= ~NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2;
2879                 }
2880         }
2881         
2882         {
2883                 /* Convert the previously used ntree->inputs/ntree->outputs lists to interface nodes.
2884                  * Pre 2.56.2 node trees automatically have all unlinked sockets exposed already
2885                  * (see NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2).
2886                  *
2887                  * XXX this should actually be part of do_versions,
2888                  * but needs valid typeinfo pointers to create interface nodes.
2889                  *
2890                  * Note: theoretically only needed in node groups (main->nodetree),
2891                  * but due to a temporary bug such links could have been added in all trees,
2892                  * so have to clean up all of them ...
2893                  */
2894                 
2895                 FOREACH_NODETREE(main, ntree, id) {
2896                         if (ntree->flag & NTREE_DO_VERSIONS_CUSTOMNODES_GROUP) {
2897                                 bNode *input_node = NULL, *output_node = NULL;
2898                                 int num_inputs = 0, num_outputs = 0;
2899                                 bNodeLink *link, *next_link;
2900                                 /* Only create new interface nodes for actual older files.
2901                                  * New file versions already have input/output nodes with duplicate links,
2902                                  * in that case just remove the invalid links.
2903                                  */
2904                                 const bool create_io_nodes = (ntree->flag & NTREE_DO_VERSIONS_CUSTOMNODES_GROUP_CREATE_INTERFACE) != 0;
2905                                 
2906                                 float input_locx = 1000000.0f, input_locy = 0.0f;
2907                                 float output_locx = -1000000.0f, output_locy = 0.0f;
2908                                 /* rough guess, not nice but we don't have access to UI constants here ... */
2909                                 static const float offsetx = 42 + 3*20 + 20;
2910                                 /*static const float offsety = 0.0f;*/
2911                                 
2912                                 if (create_io_nodes) {
2913                                         if (ntree->inputs.first)
2914                                                 input_node = nodeAddStaticNode(NULL, ntree, NODE_GROUP_INPUT);
2915                                         
2916                                         if (ntree->outputs.first)
2917                                                 output_node = nodeAddStaticNode(NULL, ntree, NODE_GROUP_OUTPUT);
2918                                 }
2919                                 
2920                                 /* Redirect links from/to the node tree interface to input/output node.
2921                                  * If the fromnode/tonode pointers are NULL, this means a link from/to
2922                                  * the ntree interface sockets, which need to be redirected to new interface nodes.
2923                                  */
2924                                 for (link = ntree->links.first; link; link = next_link) {
2925                                         bool free_link = false;
2926                                         next_link = link->next;
2927                                         
2928                                         if (link->fromnode == NULL) {
2929                                                 if (input_node) {
2930                                                         link->fromnode = input_node;
2931                                                         link->fromsock = node_group_input_find_socket(input_node, link->fromsock->identifier);
2932                                                         ++num_inputs;
2933                                                         
2934                                                         if (link->tonode) {
2935                                                                 if (input_locx > link->tonode->locx - offsetx)
2936                                                                         input_locx = link->tonode->locx - offsetx;
2937                                                                 input_locy += link->tonode->locy;
2938                                                         }
2939                                                 }
2940                                                 else {
2941                                                         free_link = true;
2942                                                 }
2943                                         }
2944                                         
2945                                         if (link->tonode == NULL) {
2946                                                 if (output_node) {
2947                                                         link->tonode = output_node;
2948                                                         link->tosock = node_group_output_find_socket(output_node, link->tosock->identifier);
2949                                                         ++num_outputs;
2950                                                         
2951                                                         if (link->fromnode) {
2952                                                                 if (output_locx < link->fromnode->locx + offsetx)
2953                                                                         output_locx = link->fromnode->locx + offsetx;
2954                                                                 output_locy += link->fromnode->locy;
2955                                                         }
2956                                                 }
2957                                                 else {
2958                                                         free_link = true;
2959                                                 }
2960                                         }
2961                                         
2962                                         if (free_link)
2963                                                 nodeRemLink(ntree, link);
2964                                 }
2965                                 
2966                                 if (num_inputs > 0) {
2967                                         input_locy /= num_inputs;
2968                                         input_node->locx = input_locx;
2969                                         input_node->locy = input_locy;
2970                                 }
2971                                 if (num_outputs > 0) {
2972                                         output_locy /= num_outputs;
2973                                         output_node->locx = output_locx;
2974                                         output_node->locy = output_locy;
2975                                 }
2976                                 
2977                                 /* clear do_versions flags */
2978                                 ntree->flag &= ~(NTREE_DO_VERSIONS_CUSTOMNODES_GROUP | NTREE_DO_VERSIONS_CUSTOMNODES_GROUP_CREATE_INTERFACE);
2979                         }
2980                 }
2981                 FOREACH_NODETREE_END
2982         }
2983         
2984         /* verify all group user nodes */
2985         for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2986                 ntreeVerifyNodes(main, &ntree->id);
2987         }
2988         
2989         /* make update calls where necessary */
2990         {
2991                 FOREACH_NODETREE(main, ntree, id) {
2992                         /* make an update call for the tree */
2993                         ntreeUpdateTree(main, ntree);
2994                 } FOREACH_NODETREE_END
2995         }
2996 }
2997
2998 static void direct_link_node_socket(FileData *fd, bNodeSocket *sock)
2999 {
3000         sock->prop = newdataadr(fd, sock->prop);
3001         IDP_DirectLinkGroup_OrFree(&sock->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3002         
3003         sock->link = newdataadr(fd, sock->link);
3004         sock->typeinfo = NULL;
3005         sock->storage = newdataadr(fd, sock->storage);
3006         sock->default_value = newdataadr(fd, sock->default_value);
3007         sock->cache = NULL;
3008 }
3009
3010 /* ntree itself has been read! */
3011 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
3012 {
3013         /* note: writing and reading goes in sync, for speed */
3014         bNode *node;
3015         bNodeSocket *sock;
3016         bNodeLink *link;
3017         
3018         ntree->init = 0;                /* to set callbacks and force setting types */
3019         ntree->is_updating = false;
3020         ntree->typeinfo= NULL;
3021         ntree->interface_type = NULL;
3022         
3023         ntree->progress = NULL;
3024         ntree->execdata = NULL;
3025         ntree->duplilock = NULL;
3026
3027         ntree->adt = newdataadr(fd, ntree->adt);
3028         direct_link_animdata(fd, ntree->adt);
3029         
3030         ntree->id.tag &= ~(LIB_TAG_ID_RECALC|LIB_TAG_ID_RECALC_DATA);
3031
3032         link_list(fd, &ntree->nodes);
3033         for (node = ntree->nodes.first; node; node = node->next) {
3034                 node->typeinfo = NULL;
3035                 
3036                 link_list(fd, &node->inputs);
3037                 link_list(fd, &node->outputs);
3038                 
3039                 node->prop = newdataadr(fd, node->prop);
3040                 IDP_DirectLinkGroup_OrFree(&node->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3041                 
3042                 link_list(fd, &node->internal_links);
3043                 for (link = node->internal_links.first; link; link = link->next) {
3044                         link->fromnode = newdataadr(fd, link->fromnode);
3045                         link->fromsock = newdataadr(fd, link->fromsock);
3046                         link->tonode = newdataadr(fd, link->tonode);
3047                         link->tosock = newdataadr(fd, link->tosock);
3048                 }
3049                 
3050                 if (node->type == CMP_NODE_MOVIEDISTORTION) {
3051                         node->storage = newmclipadr(fd, node->storage);
3052                 }
3053                 else {
3054                         node->storage = newdataadr(fd, node->storage);
3055                 }
3056                 
3057                 if (node->storage) {
3058                         /* could be handlerized at some point */
3059                         if (ntree->type==NTREE_SHADER) {
3060                                 if (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB) {
3061                                         direct_link_curvemapping(fd, node->storage);
3062                                 }
3063                                 else if (node->type==SH_NODE_SCRIPT) {
3064                                         NodeShaderScript *nss = (NodeShaderScript *) node->storage;
3065                                         nss->bytecode = newdataadr(fd, nss->bytecode);
3066                                 }
3067                                 else if (node->type==SH_NODE_TEX_POINTDENSITY) {
3068                                         NodeShaderTexPointDensity *npd = (NodeShaderTexPointDensity *) node->storage;
3069                                         memset(&npd->pd, 0, sizeof(npd->pd));
3070                                 }
3071                         }
3072                         else if (ntree->type==NTREE_COMPOSIT) {
3073                                 if (ELEM(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
3074                                         direct_link_curvemapping(fd, node->storage);
3075                                 else if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
3076                                         ((ImageUser *)node->storage)->ok = 1;
3077                         }
3078                         else if ( ntree->type==NTREE_TEXTURE) {
3079                                 if (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
3080                                         direct_link_curvemapping(fd, node->storage);
3081                                 else if (node->type==TEX_NODE_IMAGE)
3082                                         ((ImageUser *)node->storage)->ok = 1;
3083                         }
3084                 }
3085         }
3086         link_list(fd, &ntree->links);
3087         
3088         /* and we connect the rest */
3089         for (node = ntree->nodes.first; node; node = node->next) {
3090                 node->parent = newdataadr(fd, node->parent);
3091                 node->lasty = 0;
3092                 
3093                 for (sock = node->inputs.first; sock; sock = sock->next)
3094                         direct_link_node_socket(fd, sock);
3095                 for (sock = node->outputs.first; sock; sock = sock->next)
3096                         direct_link_node_socket(fd, sock);
3097         }
3098         
3099         /* interface socket lists */
3100         link_list(fd, &ntree->inputs);
3101         link_list(fd, &ntree->outputs);
3102         for (sock = ntree->inputs.first; sock; sock = sock->next)
3103                 direct_link_node_socket(fd, sock);
3104         for (sock = ntree->outputs.first; sock; sock = sock->next)
3105                 direct_link_node_socket(fd, sock);
3106         
3107         for (link = ntree->links.first; link; link= link->next) {
3108                 link->fromnode = newdataadr(fd, link->fromnode);
3109                 link->tonode = newdataadr(fd, link->tonode);
3110                 link->fromsock = newdataadr(fd, link->fromsock);
3111                 link->tosock = newdataadr(fd, link->tosock);
3112         }
3113         
3114 #if 0
3115         if (ntree->previews) {
3116                 bNodeInstanceHash *new_previews = BKE_node_instance_hash_new("node previews");
3117                 bNodeInstanceHashIterator iter;
3118                 
3119                 NODE_INSTANCE_HASH_ITER(iter, ntree->previews) {
3120                         bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
3121                         if (preview) {
3122                                 bNodePreview *new_preview = newimaadr(fd, preview);
3123                                 if (new_preview) {
3124                                         bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter);
3125                                         BKE_node_instance_hash_insert(new_previews, key, new_preview);
3126                                 }
3127                         }
3128                 }
3129                 BKE_node_instance_hash_free(ntree->previews, NULL);
3130                 ntree->previews = new_previews;
3131         }
3132 #else
3133         /* XXX TODO */
3134         ntree->previews = NULL;
3135 #endif
3136         
3137         /* type verification is in lib-link */
3138 }
3139
3140 /* ************ READ ARMATURE ***************** */
3141
3142 /* temp struct used to transport needed info to lib_link_constraint_cb() */
3143 typedef struct tConstraintLinkData {
3144         FileData *fd;
3145         ID *id;
3146 } tConstraintLinkData;
3147 /* callback function used to relink constraint ID-links */
3148 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, bool is_reference, void *userdata)
3149 {
3150         tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
3151         
3152         /* for reference types, we need to increment the usercounts on load... */
3153         if (is_reference) {
3154                 /* reference type - with usercount */
3155                 *idpoin = newlibadr_us(cld->fd, cld->id->lib, *idpoin);
3156         }
3157         else {
3158                 /* target type - no usercount needed */
3159                 *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
3160         }
3161 }
3162
3163 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
3164 {
3165         tConstraintLinkData cld;
3166         bConstraint *con;
3167         
3168         /* legacy fixes */
3169         for (con = conlist->first; con; con=con->next) {
3170                 /* patch for error introduced by changing constraints (dunno how) */
3171                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
3172                 if (con->data == NULL) {
3173                         con->type = CONSTRAINT_TYPE_NULL;
3174                 }
3175                 /* own ipo, all constraints have it */
3176                 con->ipo = newlibadr_us(fd, id->lib, con->ipo); // XXX deprecated - old animation system
3177         }
3178         
3179         /* relink all ID-blocks used by the constraints */
3180         cld.fd = fd;
3181         cld.id = id;
3182         
3183         BKE_constraints_id_loop(conlist, lib_link_constraint_cb, &cld);
3184 }
3185
3186 static void direct_link_constraints(FileData *fd, ListBase *lb)
3187 {
3188   &