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