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