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