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