Blender V5.3
source/blender/blenkernel/intern/image.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <algorithm>
10#include <cctype>
11#include <cmath>
12#include <cstdio>
13#include <cstring>
14#include <ctime>
15#include <fcntl.h>
16#include <optional>
17#ifndef WIN32
18# include <unistd.h>
19#else
20# include <io.h>
21#endif
22
23#include <regex>
24#include <string>
25
26#include "BLI_array.hh"
27#include "BLI_fileops.hh"
28#include "BLI_listbase.hh"
29#include "BLI_path_utils.hh"
30#include "BLI_rect.hh"
31#include "BLI_set.hh"
32#include "BLI_string.hh"
33#include "BLI_string_utils.hh"
34
35#include "CLG_log.h"
36
37#include "MEM_guardedalloc.h"
38
39#include "IMB_cache.hh"
41#include "IMB_imbuf.hh"
42#include "IMB_imbuf_types.hh"
43#include "IMB_metadata.hh"
44#include "IMB_openexr.hh"
45#include "IMB_partial_update.hh"
46
47#include "MOV_read.hh"
48
49/* Allow using deprecated functionality for .blend file I/O. */
50#define DNA_DEPRECATED_ALLOW
51
52#include "DNA_brush_types.h"
53#include "DNA_camera_types.h"
54#include "DNA_image_types.h"
55#include "DNA_light_types.h"
56#include "DNA_material_types.h"
57#include "DNA_object_types.h"
59#include "DNA_scene_types.h"
60#include "DNA_sequence_types.h"
61#include "DNA_userdef_types.h"
63#include "DNA_world_types.h"
64
65#include "BLI_math_vector_c.hh"
66#include "BLI_mempool.hh"
67#include "BLI_string_utf8.hh"
68#include "BLI_system.hh"
69#include "BLI_task_c.hh"
70#include "BLI_threads.hh"
71#include "BLI_time.hh"
72#include "BLI_timecode.hh" /* For stamp time-code format. */
73#include "BLI_utildefines.hh"
74
75#include "BLT_translation.hh"
76
77#include "BKE_bpath.hh"
78#include "BKE_colortools.hh"
79#include "BKE_global.hh"
80#include "BKE_icons.hh"
81#include "BKE_idtype.hh"
82#include "BKE_image.hh"
83#include "BKE_image_format.hh"
84#include "BKE_image_gpu.hh"
85#include "BKE_lib_id.hh"
86#include "BKE_library.hh"
87#include "BKE_main.hh"
88#include "BKE_node.hh"
90#include "BKE_node_runtime.hh"
92#include "BKE_packedFile.hh"
93#include "BKE_preview_image.hh"
94#include "BKE_report.hh"
95#include "BKE_scene.hh"
96#include "BKE_workspace.hh"
97
98#include "BLF_api.hh"
99
100#include "RE_pipeline.h"
101
102#include "SEQ_utils.hh" /* SEQ_get_topmost_sequence() */
103
104#include "GPU_material.hh"
105
106#include "BLI_sys_types.hh" /* for intptr_t support */
107
108#include "DEG_depsgraph.hh"
109#include "DEG_depsgraph_query.hh"
110
111#include "DRW_engine.hh"
112
113#include "BLO_read_write.hh"
114
115/* for image user iteration */
116#include "DNA_node_types.h"
117#include "DNA_screen_types.h"
118#include "DNA_space_types.h"
119
120#include "image_intern.hh"
121
122namespace blender {
123
124static CLG_LogRef LOG = {"image"};
125
126static void image_init(Image *ima, eImageSource source, eImageType type);
127static void image_free_packedfiles(Image *ima);
128static void image_free_autosave_packedfiles(Image *ima);
129static void copy_image_packedfiles(ListBaseT<ImagePackedFile> *lb_dst,
130 const ListBaseT<ImagePackedFile> *lb_src);
131
132/* -------------------------------------------------------------------- */
135
136static void image_init_data(ID *id)
137{
138 Image *image = id_cast<Image *>(id);
139
140 if (image != nullptr) {
142 }
143}
144
145static void image_copy_data(Main * /*bmain*/,
146 std::optional<Library *> /*owner_library*/,
147 ID *id_dst,
148 const ID *id_src,
149 const int flag)
150{
151 const Image *image_src = id_cast<const Image *>(id_src);
152 Image *image_dst = id_cast<Image *>(id_dst);
153 image_dst->runtime = MEM_new<bke::ImageRuntime>(__func__);
154
155 BKE_color_managed_colorspace_settings_copy(&image_dst->colorspace_settings,
156 &image_src->colorspace_settings);
157
158 copy_image_packedfiles(&image_dst->packedfiles, &image_src->packedfiles);
159 copy_image_packedfiles(&image_dst->autosave_packedfiles, &image_src->autosave_packedfiles);
160
161 image_dst->stereo3d_format = static_cast<Stereo3dFormat *>(
162 MEM_dupalloc(image_src->stereo3d_format));
163 BLI_duplicatelist(&image_dst->views, &image_src->views);
164
165 /* Cleanup stuff that cannot be copied. */
166 image_dst->rr = nullptr;
167
168 BLI_duplicatelist(&image_dst->renderslots, &image_src->renderslots);
169 for (RenderSlot &slot : image_dst->renderslots) {
170 slot.render = nullptr;
171 }
172
173 image_dst->anims.clear_no_delete();
174
175 BLI_duplicatelist(&image_dst->tiles, &image_src->tiles);
176
177 if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
178 BKE_previewimg_id_copy(&image_dst->id, &image_src->id);
179 }
180 else {
181 image_dst->preview = nullptr;
182 }
183}
184
185static void image_free_data(ID *id)
186{
187 Image *image = id_cast<Image *>(id);
188
189 /* Also frees animations (#Image.anims list). */
191
194
195 for (RenderSlot &slot : image->renderslots) {
196 if (slot.render) {
198 slot.render = nullptr;
199 }
200 }
201 image->renderslots.free_no_destruct();
202
204 MEM_SAFE_DELETE(image->stereo3d_format);
205
208
209 image->tiles.free_no_destruct();
210
211 MEM_delete(image->runtime);
212}
213
214static void image_foreach_cache(ID *id,
215 IDTypeForeachCacheFunctionCallback function_callback,
216 void *user_data)
217{
218 Image *image = id_cast<Image *>(id);
219 IDCacheKey key;
220 key.id_session_uid = id->session_uid;
221
222 key.identifier = offsetof(Image, anims.first_);
223 function_callback(id, &key, &image->anims.first_, 0, user_data);
224 key.identifier = offsetof(Image, anims.last_);
225 function_callback(id, &key, &image->anims.last_, 0, user_data);
226
227 key.identifier = offsetof(Image, rr);
228 function_callback(id, &key, reinterpret_cast<void **>(&image->rr), 0, user_data);
229
230 for (RenderSlot &slot : image->renderslots) {
231 key.identifier = size_t(BLI_ghashutil_strhash_p(slot.name));
232 function_callback(id, &key, reinterpret_cast<void **>(&slot.render), 0, user_data);
233 }
234
235 /* Ensure we don't collide with the identifiers used above. */
236 constexpr size_t runtime_base_id = size_t(1) << 32u;
237
238 key.identifier = runtime_base_id + offsetof(bke::ImageRuntime, cache);
239 function_callback(id, &key, reinterpret_cast<void **>(&image->runtime->cache), 0, user_data);
240}
241
243 const char *source_filepath_abs,
244 const char *cache_dir)
245{
246 bpath_data->is_cache = true;
247 bpath_data->is_expanded = true;
249 source_filepath_abs, cache_dir, [&](StringRef cache_filepath) {
250 char cache_path[FILE_MAX];
251 cache_filepath.copy_utf8_truncated(cache_path);
252 BKE_bpath_foreach_path_readonly_process(bpath_data, cache_path);
253 });
254 bpath_data->is_expanded = false;
255 bpath_data->is_cache = false;
256}
257
259 const char *expanded_path,
260 const eBPathForeachFlag flag)
261{
262 bpath_data->is_expanded = true;
263 BKE_bpath_foreach_path_readonly_process(bpath_data, expanded_path);
265 image_foreach_texture_cache_path(bpath_data, expanded_path, U.texture_cachedir);
266 }
267 bpath_data->is_expanded = false;
268}
269
270static void image_foreach_path(ID *id, BPathForeachPathData *bpath_data)
271{
272 Image *ima = id_cast<Image *>(id);
273 const eBPathForeachFlag flag = bpath_data->flag;
274
276 return;
277 }
278 /* Skip empty file paths, these are typically from generated images and
279 * don't make sense to add directories to until the image has been saved
280 * once to give it a meaningful value. */
281 /* TODO re-assess whether this behavior is desired in the new generic code context. */
283 return;
284 }
285
286 char abs_filepath[FILE_MAX];
287 STRNCPY(abs_filepath, ima->filepath);
288 if (bpath_data->absolute_base_path) {
289 BLI_path_abs(abs_filepath, bpath_data->absolute_base_path);
290 }
291 else {
292 BLI_path_abs(abs_filepath, ID_BLEND_PATH(bpath_data->bmain, &ima->id));
293 }
294
295 if (ima->source == IMA_SRC_TILED && (flag & BKE_BPATH_FOREACH_PATH_EXPAND_TOKENS)) {
296 /* Expand all UDIM tiles. */
297 eUDIM_TILE_FORMAT tile_format;
298 char *udim_pattern = BKE_image_get_tile_strformat(abs_filepath, &tile_format);
299 if (tile_format != UDIM_TILE_FORMAT_NONE) {
300 for (const ImageTile &tile : ima->tiles) {
301 char tile_filepath[FILE_MAX];
303 tile_filepath, udim_pattern, tile_format, tile.tile_number);
304 if (BLI_is_file(tile_filepath)) {
305 image_foreach_expanded_path(bpath_data, tile_filepath, flag);
306 }
307 }
308 }
309 MEM_SAFE_DELETE(udim_pattern);
310 return;
311 }
312
313 if (ima->source == IMA_SRC_SEQUENCE && (flag & BKE_BPATH_FOREACH_PATH_EXPAND_SEQUENCES)) {
314 /* Expand all image sequence frames. */
315 BKE_bpath_sequence_filepaths_foreach(abs_filepath, [&](StringRef frame_filepath) {
316 char frame_path[FILE_MAX];
317 frame_filepath.copy_utf8_truncated(frame_path);
318 image_foreach_expanded_path(bpath_data, frame_path, flag);
319 });
320 return;
321 }
322
323 /* If this is a tiled image, and we're asked to resolve the tokens in the virtual
324 * filepath, use the first tile to generate a concrete path for use during processing. */
325 bool result = false;
326 if (ima->source == IMA_SRC_TILED && (flag & BKE_BPATH_FOREACH_PATH_RESOLVE_TOKEN) != 0) {
327 char temp_path[FILE_MAX], orig_file[FILE_MAXFILE];
328 STRNCPY(temp_path, ima->filepath);
329 BLI_path_split_file_part(temp_path, orig_file, sizeof(orig_file));
330
331 eUDIM_TILE_FORMAT tile_format;
332 char *udim_pattern = BKE_image_get_tile_strformat(temp_path, &tile_format);
334 temp_path, udim_pattern, tile_format, (ima->tiles.first())->tile_number);
335 MEM_SAFE_DELETE(udim_pattern);
336
337 result = BKE_bpath_foreach_path_fixed_process(bpath_data, temp_path, sizeof(temp_path));
338 if (result) {
339 /* Put the filepath back together using the new directory and the original file name. */
340 char new_dir[FILE_MAXDIR];
341 BLI_path_split_dir_part(temp_path, new_dir, sizeof(new_dir));
342 BLI_path_join(ima->filepath, sizeof(ima->filepath), new_dir, orig_file);
343 }
344 }
345 else {
347 bpath_data, ima->filepath, sizeof(ima->filepath));
348 }
349
350 /* Also emit the cache file paths for the (non-expanded) source path. */
353 {
354 image_foreach_texture_cache_path(bpath_data, abs_filepath, U.texture_cachedir);
355 }
356
357 if (result) {
359 if (!BKE_image_has_packedfile(ima) &&
360 /* Image may have been painted onto (and not saved, #44543). */
361 !BKE_image_is_dirty(ima))
362 {
363 BKE_image_signal(bpath_data->bmain, ima, nullptr, IMA_SIGNAL_RELOAD);
364 }
365 }
366 }
367}
368
369static void image_blend_write(BlendWriter *writer, ID *id, const void *id_address)
370{
371 Image *ima = id_cast<Image *>(id);
372 const bool is_undo = writer->is_undo();
373
374 /* Clear all data that isn't read to reduce false detection of changed image during memfile undo.
375 */
376 ima->runtime = nullptr;
377
378 ima->anims.clear_no_delete();
379
380 ImagePackedFile *imapf;
381
382 BLI_assert(ima->packedfile == nullptr);
383 if (!is_undo) {
384 /* Do not store packed files in case this is a library override ID. */
385 if (ID_IS_OVERRIDE_LIBRARY(ima)) {
386 ima->packedfiles.clear_no_delete();
387 ima->autosave_packedfiles.clear_no_delete();
388 }
389 else {
390 /* Some trickery to keep forward compatibility of packed images. */
391 if (ima->packedfiles.first() != nullptr) {
392 imapf = ima->packedfiles.first();
393 ima->packedfile = imapf->packedfile;
394 }
395 }
396 }
397
398 /* write LibData */
399 writer->write_id_struct(id_address, ima);
400 BKE_id_blend_write(writer, &ima->id);
401
402 for (ImagePackedFile &imapf : ima->packedfiles) {
403 writer->write_struct(&imapf);
405 }
406 for (ImagePackedFile &imapf : ima->autosave_packedfiles) {
407 writer->write_struct(&imapf);
409 }
410
411 BKE_previewimg_blend_write(writer, ima->preview);
412
413 for (ImageView &iv : ima->views) {
414 writer->write_struct(&iv);
415 }
416 writer->write_struct(ima->stereo3d_format);
417
418 writer->write_struct_list(&ima->tiles, [&](BlendStructWriter<ImageTile> &struct_writer) {
419 if (!is_undo) {
420 struct_writer.shallow_data.runtime = {};
421 }
422 });
423
424 ima->packedfile = nullptr;
425
426 writer->write_struct_list(&ima->renderslots);
427}
428
429static void image_blend_read_data(BlendDataReader *reader, ID *id)
430{
431 Image *ima = id_cast<Image *>(id);
432 BLO_read_struct_list(reader, ImageTile, &ima->tiles);
433
434 BLO_read_struct_list(reader, RenderSlot, &(ima->renderslots));
435 if (!BLO_read_data_is_undo(reader)) {
436 /* We reset this last render slot index only when actually reading a file, not for undo. */
437 ima->last_render_slot = ima->render_slot;
438 }
439
440 BLO_read_struct_list(reader, ImageView, &(ima->views));
441 BLO_read_struct_list(reader, ImagePackedFile, &(ima->packedfiles));
442
443 if (ima->packedfiles.first()) {
444 for (ImagePackedFile &imapf : ima->packedfiles.items_mutable()) {
445 BKE_packedfile_blend_read(reader, &imapf.packedfile, imapf.filepath);
446 if (!imapf.packedfile) {
447 BLI_remlink(&ima->packedfiles, &imapf);
448 MEM_delete(&imapf);
449 }
450 }
451 ima->packedfile = nullptr;
452 }
453 else {
454 BKE_packedfile_blend_read(reader, &ima->packedfile, ima->filepath);
455 }
456
457 BLO_read_struct_list(reader, ImagePackedFile, &ima->autosave_packedfiles);
458 if (ima->autosave_packedfiles.first()) {
459 for (ImagePackedFile &imapf : ima->autosave_packedfiles.items_mutable()) {
460 BKE_packedfile_blend_read(reader, &imapf.packedfile, imapf.filepath);
461 if (!imapf.packedfile) {
462 BLI_remlink(&ima->autosave_packedfiles, &imapf);
463 MEM_delete(&imapf);
464 }
465 }
466 }
467
468 ima->anims.clear_no_delete();
469 BLO_read_struct(reader, PreviewImage, &ima->preview);
470 BKE_previewimg_blend_read(reader, ima->preview);
471 BLO_read_struct(reader, Stereo3dFormat, &ima->stereo3d_format);
472
473 ima->runtime = MEM_new<bke::ImageRuntime>(__func__);
474}
475
477{
478 Image *ima = reinterpret_cast<Image *>(id);
479
480 if (!BLO_read_lib_is_undo(reader)) {
483 "An image should never be marked as temporary packed after loading");
484 BLI_assert_msg(BLI_listbase_count(&ima->autosave_packedfiles) == 0,
485 "An image should never have autosave data after loading");
486 }
487
488 /* Images have some kind of 'main' cache, when null we should also clear all others. */
489 /* Needs to be done *after* cache pointers are restored (call to
490 * `foreach_cache`/`blo_cache_storage_entry_restore_in_new`), easier for now to do it in
491 * lib_link... */
492 if (ima->runtime->cache == nullptr) {
494 }
495}
496
498 .id_code = Image::id_type,
499 .id_filter = FILTER_ID_IM,
500 .dependencies_id_types = 0,
501 .main_listbase_index = INDEX_ID_IM,
502 .struct_size = sizeof(Image),
503 .name = "Image",
504 .name_plural = N_("images"),
505 .translation_context = BLT_I18NCONTEXT_ID_IMAGE,
507 .asset_type_info = nullptr,
508
509 .init_data = image_init_data,
510 .copy_data = image_copy_data,
511 .free_data = image_free_data,
512 .make_local = nullptr,
513 .foreach_id = nullptr,
514 .foreach_cache = image_foreach_cache,
515 .foreach_path = image_foreach_path,
516 .foreach_working_space_color = nullptr,
517 .foreach_asset_weak_reference = nullptr,
518 .owner_pointer_get = nullptr,
519
520 .blend_write = image_blend_write,
521 .blend_read_data = image_blend_read_data,
522 .blend_read_after_liblink = image_blend_read_after_liblink,
523
524 .blend_read_undo_preserve = nullptr,
525
526 .lib_override_apply_post = nullptr,
527};
528
529/* prototypes */
530static int image_num_viewfiles(Image *ima);
531static ImBuf *image_load_image_file(
532 Image *ima, ImageUser *iuser, int entry, int cfra, bool is_sequence);
533static ImBuf *image_acquire_ibuf(Image *ima,
534 ImageUser *iuser,
535 void **r_lock,
536 const bool ensure_host_buffer,
537 bool *r_load_failed = nullptr,
538 const bool cached_only = false);
539static void image_update_views_format(Image *ima, ImageUser *iuser);
540static void image_add_view(Image *ima, const char *viewname, const char *filepath);
541
543
544/* -------------------------------------------------------------------- */
547
548static uint imagecache_hashhash(const void *key_v)
549{
550 const ImageCacheKey *key = static_cast<const ImageCacheKey *>(key_v);
551 return key->index;
552}
553
554static bool imagecache_hashcmp(const void *a_v, const void *b_v)
555{
556 const ImageCacheKey *a = static_cast<const ImageCacheKey *>(a_v);
557 const ImageCacheKey *b = static_cast<const ImageCacheKey *>(b_v);
558
559 return (a->index != b->index);
560}
561
562static void imagecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
563{
564 ImageCacheKey *key = static_cast<ImageCacheKey *>(userkey);
565
566 *framenr = IMA_INDEX_ENTRY(key->index);
567 *proxy = IMB_PROXY_NONE;
568 *render_flags = 0;
569}
570
572{
573 if (image->runtime->cache == nullptr) {
574 // char cache_name[64];
575 // SNPRINTF_UTF8(cache_name, "Image Datablock %s", image->id.name);
576
577 image->runtime->cache = IMB_cache_create(
578 "Image Datablock Cache", sizeof(ImageCacheKey), imagecache_hashhash, imagecache_hashcmp);
580 }
581
582 if (ibuf != nullptr) {
584 }
585
586 IMB_cache_put(image->runtime->cache, &key, ibuf);
587}
588
590{
591 if (image->runtime->cache == nullptr) {
592 return;
593 }
594
595 IMB_cache_remove(image->runtime->cache, &key);
596}
597
598static ImBuf *imagecache_get(Image *image, ImageCacheKey key, bool *r_is_cached_empty)
599{
600 if (image->runtime->cache) {
601 ImBuf *ibuf = IMB_cache_get(image->runtime->cache, &key, r_is_cached_empty);
602 if (ibuf != nullptr) {
604 }
605 return ibuf;
606 }
607
608 return nullptr;
609}
610
612
613/* -------------------------------------------------------------------- */
616
618{
619 if (image->runtime->cache) {
620 IMB_cache_free(image->runtime->cache);
621 image->runtime->cache = nullptr;
622 }
623}
624
626{
627 while (ima->packedfiles.last()) {
628 ImagePackedFile *imapf = ima->packedfiles.last();
629 if (imapf->packedfile) {
631 }
632 BLI_remlink(&ima->packedfiles, imapf);
633 MEM_delete(imapf);
634 }
635}
636
641
643{
644 while (ima->autosave_packedfiles.last()) {
645 ImagePackedFile *imapf = ima->autosave_packedfiles.last();
646 if (imapf->packedfile) {
648 }
649 BLI_remlink(&ima->autosave_packedfiles, imapf);
650 MEM_delete(imapf);
651 }
652}
653
659
661{
662 image->views.free_no_destruct();
663}
664
665static void image_free_anims(Image *ima)
666{
667 while (ima->anims.last()) {
668 ImageAnim *ia = ima->anims.last();
669 if (ia->anim) {
670 MOV_close(ia->anim);
671 ia->anim = nullptr;
672 }
673 BLI_remlink(&ima->anims, ia);
674 MEM_delete(ia);
675 }
676}
677
678void BKE_image_free_buffers_ex(Image *ima, bool do_lock)
679{
680 if (do_lock) {
681 ima->runtime->cache_mutex.lock();
682 }
684
685 image_free_anims(ima);
686
687 if (ima->rr) {
688 RE_FreeRenderResult(ima->rr);
689 ima->rr = nullptr;
690 }
691
692 if (do_lock) {
693 ima->runtime->cache_mutex.unlock();
694 }
695}
696
698{
699 BKE_image_free_buffers_ex(ima, false);
700}
701
702/* Gather image buffers used by a multilayer image. */
704{
705 Set<const ImBuf *> buffers;
706 if (ima.type != IMA_TYPE_MULTILAYER || ima.rr == nullptr) {
707 return buffers;
708 }
709 for (const RenderLayer &rl : ima.rr->layers) {
710 for (const RenderPass &rpass : rl.passes) {
711 if (rpass.ibuf) {
712 buffers.add(rpass.ibuf);
713 }
714 }
715 }
716 return buffers;
717}
718
720{
721 static int64_t lasttime = 0;
722 const int64_t ctime = BLI_time_now_seconds_i();
723
724 /*
725 * Run garbage collector once for every collecting period of time
726 * if textimeout is 0, that's the option to NOT run the collector
727 */
728 if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime) {
729 return;
730 }
731
732 /* of course not! */
733 if (G.is_rendering) {
734 return;
735 }
736
737 lasttime = ctime;
738
739 for (Image &ima : bmain->images) {
740 if ((ima.flag & IMA_NOCOLLECT) || ima.runtime->cache == nullptr) {
741 continue;
742 }
743
744 bool any_buffer_left = false;
745 {
746 std::scoped_lock lock(ima.runtime->cache_mutex);
747
748 const Set<const ImBuf *> multilayer_ibufs = image_multilayer_ibufs(ima);
749
750 /* Gather entries to remove. */
751 Vector<ImageCacheKey> to_remove;
752 ImBufCacheIter *iter = IMB_cacheIter_new(ima.runtime->cache);
753 while (!IMB_cacheIter_done(iter)) {
754 ImBuf *ibuf = IMB_cacheIter_getImBuf(iter);
755 if (ibuf != nullptr) {
756 /* GPU buffers: free when past timeout and image buffer is not used elsewhere. */
757 bool freed_gpu = false;
758 /* Multilayer images have another reference we need to account for. */
759 const int owner_refs = multilayer_ibufs.contains(ibuf) ? 1 : 0;
760 if (ctime - ibuf->gpu.lastused > U.textimeout) {
761 if ((ibuf->gpu.texture || ibuf->gpu.flag & IMB_GPU_LOAD_FAILED) &&
762 ibuf->refcounter == owner_refs)
763 {
765 freed_gpu = true;
766 }
767 }
768
769 /* CPU buffers: free whole image buffer if past timeout, and image has not been
770 * edited and has not GPU buffers. When the GPU texture was just freed, keep the
771 * buffer for another more collection cycle to give it a chance to be reused. */
772 if (!freed_gpu && ibuf->gpu.texture == nullptr &&
773 (ibuf->userflags & IB_BITMAPDIRTY) == 0 && (ctime - ibuf->lastused > U.textimeout))
774 {
775 to_remove.append(*static_cast<const ImageCacheKey *>(IMB_cacheIter_getUserKey(iter)));
776 }
777 else {
778 any_buffer_left = true;
779 }
780 }
781 IMB_cacheIter_step(iter);
782 }
783 IMB_cacheIter_free(iter);
784
785 /* Remove entries. */
786 for (const ImageCacheKey &key : to_remove) {
787 imagecache_remove(&ima, key);
788 }
789
790 /* Also free multilayer render result when all buffers are unused. */
791 if (!any_buffer_left && !multilayer_ibufs.is_empty()) {
792 RE_FreeRenderResult(ima.rr);
793 ima.rr = nullptr;
794 }
795 }
796
797 /* If there are no buffers, also close the movie reader handles. */
798 if (!any_buffer_left && !BLI_listbase_is_empty(&ima.anims)) {
799 image_free_anims(&ima);
800 }
801 }
802}
803
805{
806 image_free_data(&ima->id);
807}
808
809static ImageTile *imagetile_alloc(int tile_number)
810{
811 ImageTile *tile = MEM_new<ImageTile>("Image Tile");
812 tile->tile_number = tile_number;
813 tile->gen_x = 1024;
814 tile->gen_y = 1024;
815 tile->gen_type = IMA_GENTYPE_GRID;
816 return tile;
817}
818
819/* only image block itself */
820static void image_init(Image *ima, eImageSource source, eImageType type)
821{
823
824 ima->source = source;
825 ima->type = type;
826
827 if (source == IMA_SRC_VIEWER) {
828 ima->flag |= IMA_VIEW_AS_RENDER;
829 }
830
832 BLI_addtail(&ima->tiles, tile);
833
834 if (type == IMA_TYPE_R_RESULT) {
835 for (int i = 0; i < 8; i++) {
836 BKE_image_add_renderslot(ima, nullptr);
837 }
838 }
839
840 ima->runtime = MEM_new<bke::ImageRuntime>(__func__);
841
842 BKE_color_managed_colorspace_settings_init(&ima->colorspace_settings);
843 ima->stereo3d_format = MEM_new<Stereo3dFormat>("Image Stereo Format");
844}
845
846static Image *image_alloc(Main *bmain,
847 std::optional<Library *> owner_library,
848 const char *name,
849 eImageSource source,
850 eImageType type)
851{
852 Image *ima;
853
854 ima = static_cast<Image *>(BKE_libblock_alloc_in_lib(bmain, owner_library, ID_IM, name, 0));
855 if (ima) {
856 image_init(ima, source, type);
857 }
858
859 return ima;
860}
861
870 int index,
871 int entry,
872 bool *r_is_cached_empty)
873{
874 if (index != IMA_NO_INDEX) {
875 index = IMA_MAKE_INDEX(entry, index);
876 }
877
878 ImageCacheKey key = {.index = index};
879 return imagecache_get(ima, key, r_is_cached_empty);
880}
881
882static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int entry)
883{
884 if (index != IMA_NO_INDEX) {
885 index = IMA_MAKE_INDEX(entry, index);
886 }
887
888 ImageCacheKey key = {.index = index};
889 imagecache_put(ima, key, ibuf);
890}
891
892static void image_remove_ibuf(Image *ima, int index, int entry)
893{
894 if (index != IMA_NO_INDEX) {
895 index = IMA_MAKE_INDEX(entry, index);
896 }
897 ImageCacheKey key = {.index = index};
898 imagecache_remove(ima, key);
899}
900
905
906static void copy_image_packedfiles(ListBaseT<ImagePackedFile> *lb_dst,
907 const ListBaseT<ImagePackedFile> *lb_src)
908{
909 const ImagePackedFile *imapf_src;
910
911 lb_dst->clear_no_delete();
912 for (imapf_src = lb_src->first(); imapf_src; imapf_src = imapf_src->next) {
913 ImagePackedFile *imapf_dst = MEM_new<ImagePackedFile>("Image Packed Files (copy)");
914
915 imapf_dst->view = imapf_src->view;
916 imapf_dst->tile_number = imapf_src->tile_number;
917 STRNCPY(imapf_dst->filepath, imapf_src->filepath);
918
919 if (imapf_src->packedfile) {
920 imapf_dst->packedfile = BKE_packedfile_duplicate(imapf_src->packedfile);
921 }
922
923 BLI_addtail(lb_dst, imapf_dst);
924 }
925}
926
927void BKE_image_merge(Main *bmain, Image *dest, Image *source)
928{
929 /* sanity check */
930 if (dest && source && dest != source) {
931 {
932 std::scoped_lock lock_src(source->runtime->cache_mutex);
933 std::scoped_lock lock_dst(dest->runtime->cache_mutex);
934
935 if (source->runtime->cache != nullptr) {
936 ImBufCacheIter *iter;
937 iter = IMB_cacheIter_new(source->runtime->cache);
938 while (!IMB_cacheIter_done(iter)) {
939 ImBuf *ibuf = IMB_cacheIter_getImBuf(iter);
940 ImageCacheKey *key = static_cast<ImageCacheKey *>(IMB_cacheIter_getUserKey(iter));
941 imagecache_put(dest, *key, ibuf);
942 IMB_cacheIter_step(iter);
943 }
944 IMB_cacheIter_free(iter);
945 }
946 }
947 BKE_id_free(bmain, source);
948 }
949}
950
951bool BKE_image_scale(Image *image, int width, int height, ImageUser *iuser)
952{
953 /* NOTE: We could be clever and scale all imbuf's
954 * but since some are mipmaps its not so simple. */
955
956 ImBuf *ibuf;
957 void *lock;
958
959 ibuf = BKE_image_acquire_ibuf(image, iuser, &lock);
960
961 if (ibuf) {
962 IMB_scale(ibuf, width, height, IMBScaleFilter::Box, false);
964 IMB_mark_dirty(ibuf);
965 }
966
968
969 return (ibuf != nullptr);
970}
971
972static int image_get_tile_number_from_iuser(const Image *ima, const ImageUser *iuser)
973{
974 BLI_assert(ima != nullptr && ima->tiles.first());
975 ImageTile *tile = ima->tiles.first();
976 return (iuser && iuser->tile) ? iuser->tile : tile->tile_number;
977}
978
979ImageTile *BKE_image_get_tile(Image *ima, int tile_number)
980{
981 if (ima == nullptr) {
982 return nullptr;
983 }
984
985 /* Tiles 0 and 1001 are a special case and refer to the first tile, typically
986 * coming from non-UDIM-aware code. */
987 if (ELEM(tile_number, 0, 1001)) {
988 return ima->tiles.first();
989 }
990
991 /* Must have a tiled image and a valid tile number at this point. */
992 if (ima->source != IMA_SRC_TILED || tile_number < 1001 || tile_number > IMA_UDIM_MAX) {
993 return nullptr;
994 }
995
996 for (ImageTile &tile : ima->tiles) {
997 if (tile.tile_number == tile_number) {
998 return &tile;
999 }
1000 }
1001
1002 return nullptr;
1003}
1004
1009
1010int BKE_image_get_tile_from_pos(Image *ima, const float uv[2], float r_uv[2], float r_ofs[2])
1011{
1012 float local_ofs[2];
1013 if (r_ofs == nullptr) {
1014 r_ofs = local_ofs;
1015 }
1016
1017 copy_v2_v2(r_uv, uv);
1018 zero_v2(r_ofs);
1019
1020 if ((ima->source != IMA_SRC_TILED) || uv[0] < 0.0f || uv[1] < 0.0f || uv[0] >= 10.0f) {
1021 return 0;
1022 }
1023
1024 int ix = int(uv[0]);
1025 int iy = int(uv[1]);
1026 int tile_number = 1001 + 10 * iy + ix;
1027
1028 if (BKE_image_get_tile(ima, tile_number) == nullptr) {
1029 return 0;
1030 }
1031 r_ofs[0] = ix;
1032 r_ofs[1] = iy;
1033 sub_v2_v2(r_uv, r_ofs);
1034
1035 return tile_number;
1036}
1037
1038void BKE_image_get_tile_uv(const Image *ima, const int tile_number, float r_uv[2])
1039{
1040 if (ima->source != IMA_SRC_TILED) {
1041 zero_v2(r_uv);
1042 }
1043 else {
1044 const int tile_index = tile_number - 1001;
1045 r_uv[0] = float(tile_index % 10);
1046 r_uv[1] = float(tile_index / 10);
1047 }
1048}
1049
1051static float distance_to_unit_interval(float x)
1052{
1053 /* The unit interval is between 0 and 1.
1054 * Within the interval, return 0.
1055 * Outside the interval, return the distance to the nearest boundary.
1056 * Intuitively, the function looks like:
1057 * \ | | /
1058 * __\|___|/__
1059 * 0 1
1060 */
1061
1062 if (x <= 0.0f) {
1063 return -x; /* Distance to left border. */
1064 }
1065 if (x <= 1.0f) {
1066 return 0.0f; /* Inside unit interval. */
1067 }
1068 return x - 1.0f; /* Distance to right border. */
1069}
1070
1072static float distance_squared_to_udim(const float co[2], const float udim[2])
1073{
1074 float delta[2];
1075 sub_v2_v2v2(delta, co, udim);
1076 delta[0] = distance_to_unit_interval(delta[0]);
1077 delta[1] = distance_to_unit_interval(delta[1]);
1078 return len_squared_v2(delta);
1079}
1080
1081static bool nearest_udim_tile_tie_break(const float best_dist_sq,
1082 const float best_uv[2],
1083 const float dist_sq,
1084 const float uv[2])
1085{
1086 if (best_dist_sq == dist_sq) { /* Exact same distance? Tie-break. */
1087 if (best_uv[0] == uv[0]) { /* Exact same U? Tie-break. */
1088 return (uv[1] > best_uv[1]); /* Higher than previous candidate? */
1089 }
1090 return (uv[0] > best_uv[0]); /* Further right than previous candidate? */
1091 }
1092 return (dist_sq < best_dist_sq); /* Closer than previous candidate? */
1093}
1094
1096 const float co[2],
1097 float r_uv_offset[2])
1098{
1099 /* NOTE: If the coordinates are integers, take special care to break ties. */
1100
1101 zero_v2(r_uv_offset);
1102 int tile_number_best = -1;
1103
1104 if (!image || image->source != IMA_SRC_TILED) {
1105 return tile_number_best;
1106 }
1107
1108 /* Distance squared to the closest UDIM tile. */
1109 float dist_best_sq = FLT_MAX;
1110
1111 for (const ImageTile &tile : image->tiles) {
1112 float uv_offset[2];
1113 BKE_image_get_tile_uv(image, tile.tile_number, uv_offset);
1114
1115 /* Distance squared between #co and closest point on UDIM tile. */
1116 const float dist_sq = distance_squared_to_udim(co, uv_offset);
1117
1118 if (dist_sq == 0) { /* Either inside in the UDIM, or on its boundary. */
1119 if (floorf(co[0]) == uv_offset[0] && floorf(co[1]) == uv_offset[1]) {
1120 /* Within the half-open interval of the UDIM. */
1121 copy_v2_v2(r_uv_offset, uv_offset);
1122 return tile_number_best;
1123 }
1124 }
1125
1126 if (nearest_udim_tile_tie_break(dist_best_sq, r_uv_offset, dist_sq, uv_offset)) {
1127 /* Tile is better than previous best, update. */
1128 dist_best_sq = dist_sq;
1129 copy_v2_v2(r_uv_offset, uv_offset);
1130 tile_number_best = tile.tile_number;
1131 }
1132 }
1133 return tile_number_best;
1134}
1135
1136int BKE_image_find_nearest_tile(const Image *image, const float co[2])
1137{
1138 float uv_offset_dummy[2];
1139 return BKE_image_find_nearest_tile_with_offset(image, co, uv_offset_dummy);
1140}
1141
1143{
1144 ImBuf *ibuf;
1145 char filepath[FILE_MAX];
1146
1147 BKE_image_user_file_path(nullptr, ima, filepath);
1148
1149 /* Will set input color space to image format default's. */
1151 filepath, ImBufFlags::Test | ImBufFlags::AlphaDetect, &ima->colorspace_settings);
1152
1153 if (ibuf) {
1154 if (flag_is_set(ibuf->flags, ImBufFlags::AlphaPremul)) {
1155 ima->alpha_mode = IMA_ALPHA_PREMUL;
1156 }
1157 else if (flag_is_set(ibuf->flags, ImBufFlags::AlphaChannelPacked)) {
1158 ima->alpha_mode = IMA_ALPHA_CHANNEL_PACKED;
1159 }
1160 else if (flag_is_set(ibuf->flags, ImBufFlags::AlphaIgnore)) {
1161 ima->alpha_mode = IMA_ALPHA_IGNORE;
1162 }
1163 else {
1164 ima->alpha_mode = IMA_ALPHA_STRAIGHT;
1165 }
1166
1167 IMB_freeImBuf(ibuf);
1168 }
1169}
1170
1172{
1173 if (BLI_path_extension_check_n(filepath, ".exr", ".cin", ".dpx", ".hdr", nullptr)) {
1174 return IMA_ALPHA_PREMUL;
1175 }
1176
1177 return IMA_ALPHA_STRAIGHT;
1178}
1179
1184
1185static void image_abs_path(Main *bmain,
1186 Library *owner_library,
1187 const char *filepath,
1188 char *r_filepath_abs)
1189{
1190 BLI_strncpy(r_filepath_abs, filepath, FILE_MAX);
1191 if (owner_library) {
1192 BLI_path_abs(r_filepath_abs, owner_library->runtime->filepath_abs);
1193 }
1194 else {
1195 BLI_path_abs(r_filepath_abs, BKE_main_blendfile_path(bmain));
1196 }
1197}
1198
1199Image *BKE_image_load(Main *bmain, const char *filepath, bool check_open)
1200{
1201 return BKE_image_load_in_lib(bmain, std::nullopt, filepath, check_open);
1202}
1203
1205 std::optional<Library *> owner_library,
1206 const char *filepath,
1207 bool check_open)
1208{
1209 Image *ima;
1210 int file;
1211 char filepath_abs[FILE_MAX];
1212
1213 /* If no owner library is explicitly given, use the current library from the given #Main. */
1214 Library *owner_lib = owner_library.value_or(bmain->curlib);
1215
1216 image_abs_path(bmain, owner_lib, filepath, filepath_abs);
1217
1218 /* Does it exist on the file-system? */
1219 if (check_open) {
1220 file = BLI_open(filepath_abs, O_BINARY | O_RDONLY, 0);
1221 if (file == -1) {
1222 if (!BKE_image_tile_filepath_exists(filepath_abs)) {
1223 return nullptr;
1224 }
1225 }
1226 else {
1227 close(file);
1228 }
1229 }
1230
1231 ima = image_alloc(
1232 bmain, owner_library, BLI_path_basename(filepath), IMA_SRC_FILE, IMA_TYPE_IMAGE);
1233 STRNCPY(ima->filepath, filepath);
1234
1236 ima->source = IMA_SRC_MOVIE;
1237 }
1238
1240
1241 return ima;
1242}
1243
1244Image *BKE_image_load_exists(Main *bmain, const char *filepath, bool check_open, bool *r_exists)
1245{
1246 return BKE_image_load_exists_in_lib(bmain, std::nullopt, filepath, check_open, r_exists);
1247}
1248
1250 std::optional<Library *> owner_library,
1251 const char *filepath,
1252 bool check_open,
1253 bool *r_exists)
1254{
1255 Image *ima;
1256 char filepath_abs[FILE_MAX], filepath_test[FILE_MAX];
1257
1258 /* If not owner library is explicitly given, use the current library from the given Main. */
1259 Library *owner_lib = owner_library.value_or(bmain->curlib);
1260
1261 image_abs_path(bmain, owner_lib, filepath, filepath_abs);
1262
1263 /* First search an identical filepath. */
1264 for (ima = bmain->images.first(); ima; ima = static_cast<Image *>(ima->id.next)) {
1265 if (!ELEM(ima->source, IMA_SRC_VIEWER, IMA_SRC_GENERATED)) {
1266 STRNCPY(filepath_test, ima->filepath);
1267 BLI_path_abs(filepath_test, ID_BLEND_PATH(bmain, &ima->id));
1268
1269 if (BLI_path_cmp(filepath_test, filepath_abs) != 0) {
1270 continue;
1271 }
1272 if (BKE_image_has_anim(ima) && (ima->id.us != 0)) {
1273 /* TODO explain why animated images with already one or more users are skipped? */
1274 continue;
1275 }
1276 if (ima->id.lib != owner_lib) {
1277 continue;
1278 }
1279 /* FIXME Should not happen here. Only code actually adding an ID usage should increment this
1280 * counter. */
1281 id_us_plus(&ima->id);
1282 if (r_exists) {
1283 *r_exists = true;
1284 }
1285 return ima;
1286 }
1287 }
1288
1289 if (r_exists) {
1290 *r_exists = false;
1291 }
1292 return BKE_image_load_in_lib(bmain, owner_library, filepath, check_open);
1293}
1294
1303
1304static void image_buf_fill_isolated(void *usersata_v)
1305{
1306 ImageFillData *usersata = static_cast<ImageFillData *>(usersata_v);
1307
1308 const short gen_type = usersata->gen_type;
1309 const uint width = usersata->width;
1310 const uint height = usersata->height;
1311
1312 uchar *rect = usersata->rect;
1313 float *rect_float = usersata->rect_float;
1314
1315 switch (gen_type) {
1316 case IMA_GENTYPE_GRID:
1317 BKE_image_buf_fill_checker(rect, rect_float, width, height);
1318 break;
1320 BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
1321 break;
1322 default:
1323 BKE_image_buf_fill_color(rect, rect_float, width, height, usersata->fill_color);
1324 break;
1325 }
1326}
1327
1329{
1330 ImBuf *ibuf;
1331 uchar *rect = nullptr;
1332 float *rect_float = nullptr;
1333 float fill_color[4];
1334
1335 ImColorMode color_mode = ImColorMode(tile->gen_depth);
1336 const bool floatbuf = (tile->gen_flag & IMA_GEN_FLOAT) != 0;
1337 if (floatbuf) {
1338 ibuf = IMB_allocImBuf(tile->gen_x, tile->gen_y, ImBufFlags::FloatData);
1339
1340 if (ima->colorspace_settings.name[0] == '\0') {
1343
1344 IMB_colormanagement_colorspace_settings_set(&ima->colorspace_settings, colorspace);
1345 }
1346
1347 if (ibuf != nullptr) {
1348 ibuf->color_mode = color_mode;
1349 rect_float = ibuf->float_data_for_write();
1350 IMB_colormanagement_assign_float_colorspace(ibuf, ima->colorspace_settings.name);
1351 }
1352
1353 if (IMB_colormanagement_space_name_is_data(ima->colorspace_settings.name)) {
1354 copy_v4_v4(fill_color, tile->gen_color);
1355 }
1356 else {
1357 /* The input color here should ideally be linear already, but for now
1358 * we just convert and postpone breaking the API for later. */
1359 srgb_to_linearrgb_v4(fill_color, tile->gen_color);
1360 }
1361 }
1362 else {
1363 ibuf = IMB_allocImBuf(tile->gen_x, tile->gen_y, ImBufFlags::ByteData);
1364
1365 if (ima->colorspace_settings.name[0] == '\0') {
1368
1369 IMB_colormanagement_colorspace_settings_set(&ima->colorspace_settings, colorspace);
1370 }
1371
1372 if (ibuf != nullptr) {
1373 ibuf->color_mode = color_mode;
1374 rect = ibuf->byte_data_for_write();
1375 IMB_colormanagement_assign_byte_colorspace(ibuf, ima->colorspace_settings.name);
1376 }
1377
1378 copy_v4_v4(fill_color, tile->gen_color);
1379 }
1380
1381 if (!ibuf) {
1382 return nullptr;
1383 }
1384
1385 char filepath[FILE_MAX];
1386 STRNCPY(filepath, ima->filepath);
1387 BLI_path_abs(filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
1388 ibuf->filepath = filepath;
1389
1390 /* Mark the tile itself as having been generated. */
1391 tile->gen_flag |= IMA_GEN_TILE;
1392
1394
1395 data.gen_type = tile->gen_type;
1396 data.width = tile->gen_x;
1397 data.height = tile->gen_y;
1398 data.rect = rect;
1399 data.rect_float = rect_float;
1400 copy_v4_v4(data.fill_color, fill_color);
1401
1403
1404 return ibuf;
1405}
1406
1408 uint width,
1409 uint height,
1410 const char *name,
1411 int depth,
1412 int floatbuf,
1413 short gen_type,
1414 const float color[4],
1415 const bool stereo3d,
1416 const bool is_data,
1417 const bool tiled)
1418{
1419 /* Saving the image changes it's #Image.source to #IMA_SRC_FILE (leave as generated here). */
1420 Image *ima;
1421 if (tiled) {
1422 ima = image_alloc(bmain, std::nullopt, name, IMA_SRC_TILED, IMA_TYPE_IMAGE);
1423 }
1424 else {
1425 ima = image_alloc(bmain, std::nullopt, name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
1426 }
1427 if (ima == nullptr) {
1428 return nullptr;
1429 }
1430
1431 int view_id;
1432 const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
1433
1434 /* NOTE: leave `ima->filepath` unset,
1435 * setting it to a dummy value may write to an invalid file-path. */
1436
1437 /* The generation info is always stored in the tiles. The first tile
1438 * will be used for non-tiled images. */
1439 ImageTile *tile = ima->tiles.first();
1440 tile->gen_x = width;
1441 tile->gen_y = height;
1442 tile->gen_type = eImageGenType(gen_type);
1443 tile->gen_flag |= eImage_GenFlag(floatbuf ? IMA_GEN_FLOAT : 0);
1444 tile->gen_depth = depth;
1445 copy_v4_v4(tile->gen_color, color);
1446
1447 if (is_data) {
1450 }
1451
1452 for (view_id = 0; view_id < 2; view_id++) {
1453 ImBuf *ibuf;
1454 ibuf = add_ibuf_for_tile(ima, tile);
1455 int index = tiled ? 0 : IMA_NO_INDEX;
1456 int entry = tiled ? 1001 : 0;
1457 image_assign_ibuf(ima, ibuf, stereo3d ? view_id : index, entry);
1458
1459 /* #image_assign_ibuf puts buffer to the cache, which increments user counter. */
1460 IMB_freeImBuf(ibuf);
1461 if (!stereo3d) {
1462 break;
1463 }
1464
1465 image_add_view(ima, names[view_id], "");
1466 }
1467
1468 return ima;
1469}
1470
1472{
1473 const char *colorspace_name = nullptr;
1474
1475 if (ibuf->float_data()) {
1476 colorspace_name = IMB_colormanagement_get_float_colorspace(ibuf);
1477 }
1478
1479 if (ibuf->byte_data() && !colorspace_name) {
1480 colorspace_name = IMB_colormanagement_get_byte_colorspace(ibuf);
1481 }
1482
1483 if (colorspace_name) {
1484 IMB_colormanagement_colorspace_settings_set(&image->colorspace_settings, colorspace_name);
1485 }
1486}
1487
1488Image *BKE_image_add_from_imbuf(Main *bmain, ImBuf *ibuf, const char *name)
1489{
1490 if (name == nullptr) {
1491 name = BLI_path_basename(ibuf->filepath.c_str());
1492 }
1493
1494 /* When the image buffer has valid path create a new image with "file" source and copy the path
1495 * from the image buffer.
1496 * Otherwise create "generated" image, avoiding invalid configuration with an empty file path. */
1497 const eImageSource source = ibuf->filepath[0] != '\0' ? IMA_SRC_FILE : IMA_SRC_GENERATED;
1498
1499 Image *ima = image_alloc(bmain, std::nullopt, name, source, IMA_TYPE_IMAGE);
1500
1501 if (!ima) {
1502 return nullptr;
1503 }
1504
1505 BKE_image_replace_imbuf(ima, ibuf);
1506
1507 return ima;
1508}
1509
1511{
1512 BLI_assert(image->type == IMA_TYPE_IMAGE &&
1514
1516
1519
1520 /* Keep generated image type flags consistent with the image buffer. */
1521 if (image->source == IMA_SRC_GENERATED) {
1522 ImageTile *base_tile = BKE_image_get_tile(image, 0);
1523 if (ibuf->float_data()) {
1524 base_tile->gen_flag |= IMA_GEN_FLOAT;
1525 }
1526 else {
1527 base_tile->gen_flag &= ~IMA_GEN_FLOAT;
1528 }
1529
1530 base_tile->gen_x = ibuf->x;
1531 base_tile->gen_y = ibuf->y;
1532 }
1533
1534 /* Consider image dirty since its content can not be re-created unless the image is explicitly
1535 * saved. */
1536 IMB_mark_dirty(ibuf);
1537}
1538
1541 Image *ima, ImBuf *ibuf, int view, int tile_number, const char *filepath)
1542{
1543 ibuf->ftype = ibuf->float_data() ? IMB_FTYPE_OPENEXR : IMB_FTYPE_PNG;
1544
1546 if (encoded.is_empty()) {
1547 CLOG_STR_ERROR(&LOG, "memory save for pack error");
1549 return false;
1550 }
1551
1552 auto *shared_data = new ImplicitSharedValue<Vector<uint8_t>>(std::move(encoded));
1554 shared_data->data.data(), int(shared_data->data.size()), shared_data);
1555
1556 ImagePackedFile *imapf = MEM_new<ImagePackedFile>("Image PackedFile");
1557 STRNCPY(imapf->filepath, filepath);
1558 imapf->packedfile = pf;
1559 imapf->view = view;
1560 imapf->tile_number = tile_number;
1561 BLI_addtail(&ima->packedfiles, imapf);
1562
1563 ibuf->userflags &= ~IB_BITMAPDIRTY;
1564
1565 return true;
1566}
1567
1569{
1570 bool ok = true;
1571
1573
1574 const int tot_viewfiles = image_num_viewfiles(ima);
1575 const bool is_tiled = (ima->source == IMA_SRC_TILED);
1576 const bool is_multiview = BKE_image_is_multiview(ima);
1577
1578 ImageUser iuser{};
1579 BKE_imageuser_default(&iuser);
1580 char tiled_filepath[FILE_MAX];
1581
1582 for (int view = 0; view < tot_viewfiles; view++) {
1583 for (ImageTile &tile : ima->tiles) {
1584 int index = (is_multiview || is_tiled) ? view : IMA_NO_INDEX;
1585 int entry = is_tiled ? tile.tile_number : 0;
1586 ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, nullptr);
1587 if (!ibuf) {
1588 ok = false;
1589 break;
1590 }
1591
1592 const char *filepath = ibuf->filepath.c_str();
1593 if (is_tiled) {
1594 iuser.tile = tile.tile_number;
1595 BKE_image_user_file_path(&iuser, ima, tiled_filepath);
1596 filepath = tiled_filepath;
1597 }
1598 else if (is_multiview) {
1599 ImageView *iv = static_cast<ImageView *>(BLI_findlink(&ima->views, view));
1600 /* if the image was a R_IMF_VIEWS_STEREO_3D we force _L, _R suffices */
1601 if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
1602 const char *suffix[2] = {STEREO_LEFT_SUFFIX, STEREO_RIGHT_SUFFIX};
1603 BLI_path_suffix(iv->filepath, FILE_MAX, suffix[view], "");
1604 }
1605 filepath = iv->filepath;
1606 }
1607
1608 ok = ok && image_memorypack_imbuf(ima, ibuf, view, tile.tile_number, filepath);
1609 IMB_freeImBuf(ibuf);
1610 }
1611 }
1612
1613 if (is_multiview) {
1614 ima->views_format = R_IMF_VIEWS_INDIVIDUAL;
1615 }
1616
1617 /* Images which were "generated" before packing should now be
1618 * treated as if they were saved as real files. */
1619 if (ok) {
1620 if (ima->source == IMA_SRC_GENERATED) {
1621 ima->source = IMA_SRC_FILE;
1622 ima->type = IMA_TYPE_IMAGE;
1623 }
1624
1625 /* Clear the per-tile generated flag if all tiles were ok.
1626 * Mirrors similar processing inside #BKE_image_save. */
1627 for (ImageTile &tile : ima->tiles) {
1628 tile.gen_flag &= ~IMA_GEN_TILE;
1629 }
1631 }
1632
1633 return ok;
1634}
1635
1638 Image *ima, ImBuf *ibuf, int view, int tile_number, const char *filepath)
1639{
1640 ibuf->ftype = ibuf->float_data() ? IMB_FTYPE_OPENEXR : IMB_FTYPE_PNG;
1641
1643 if (encoded.is_empty()) {
1644 CLOG_STR_ERROR(&LOG, "memory save for pack error");
1646 return false;
1647 }
1648
1649 auto *shared_data = new ImplicitSharedValue<Vector<uint8_t>>(std::move(encoded));
1651 shared_data->data.data(), int(shared_data->data.size()), shared_data);
1652
1653 ImagePackedFile *imapf = MEM_new<ImagePackedFile>("Image PackedFile");
1654 STRNCPY(imapf->filepath, filepath);
1655 imapf->packedfile = pf;
1656 imapf->view = view;
1657 imapf->tile_number = tile_number;
1658 BLI_addtail(&ima->autosave_packedfiles, imapf);
1659
1660 /* We should not clear the dirty flag when auto-saving. */
1661
1662 return true;
1663}
1664
1666{
1667 bool ok = true;
1668
1670
1671 const int tot_viewfiles = image_num_viewfiles(ima);
1672 const bool is_tiled = (ima->source == IMA_SRC_TILED);
1673 const bool is_multiview = BKE_image_is_multiview(ima);
1674
1675 ImageUser iuser{};
1676 BKE_imageuser_default(&iuser);
1677 char tiled_filepath[FILE_MAX];
1678
1679 for (int view = 0; view < tot_viewfiles; view++) {
1680 for (ImageTile &tile : ima->tiles) {
1681 int index = (is_multiview || is_tiled) ? view : IMA_NO_INDEX;
1682 int entry = is_tiled ? tile.tile_number : 0;
1683 ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, nullptr);
1684 if (!ibuf) {
1685 ok = false;
1686 break;
1687 }
1688
1689 const char *filepath = ibuf->filepath.c_str();
1690 if (is_tiled) {
1691 iuser.tile = tile.tile_number;
1692 BKE_image_user_file_path(&iuser, ima, tiled_filepath);
1693 filepath = tiled_filepath;
1694 }
1695 else if (is_multiview) {
1696 ImageView *iv = static_cast<ImageView *>(BLI_findlink(&ima->views, view));
1697 /* if the image was a R_IMF_VIEWS_STEREO_3D we force _L, _R suffices */
1698 if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
1699 const char *suffix[2] = {STEREO_LEFT_SUFFIX, STEREO_RIGHT_SUFFIX};
1700 BLI_path_suffix(iv->filepath, FILE_MAX, suffix[view], "");
1701 }
1702 filepath = iv->filepath;
1703 }
1704
1705 ok = ok && image_memorypack_imbuf_for_autosave(ima, ibuf, view, tile.tile_number, filepath);
1706 IMB_freeImBuf(ibuf);
1707 }
1708 }
1709
1710 if (is_multiview) {
1711 ima->views_format = R_IMF_VIEWS_INDIVIDUAL;
1712 }
1713
1714 if (ok) {
1715 ima->flag |= IMA_AUTOSAVE_TEMPPACK;
1716 }
1717
1718 return ok;
1719}
1720
1721void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath)
1722{
1723 const int tot_viewfiles = image_num_viewfiles(ima);
1724
1725 ImageUser iuser{};
1726 BKE_imageuser_default(&iuser);
1727 for (int view = 0; view < tot_viewfiles; view++) {
1728 iuser.view = view;
1729 for (ImageTile &tile : ima->tiles) {
1730 iuser.tile = tile.tile_number;
1731 char filepath[FILE_MAX];
1732 BKE_image_user_file_path(&iuser, ima, filepath);
1733
1734 ImagePackedFile *imapf = MEM_new<ImagePackedFile>("Image packed file");
1735 BLI_addtail(&ima->packedfiles, imapf);
1736
1737 imapf->packedfile = BKE_packedfile_new(reports, filepath, basepath);
1738 imapf->view = view;
1739 imapf->tile_number = tile.tile_number;
1740 if (imapf->packedfile) {
1741 STRNCPY(imapf->filepath, filepath);
1742 }
1743 else {
1744 BLI_freelinkN(&ima->packedfiles, imapf);
1745 }
1746 }
1747 }
1748
1750}
1751
1753 Image *ima,
1754 char *data,
1755 const size_t data_len)
1756{
1757 const int tot_viewfiles = image_num_viewfiles(ima);
1758
1759 if (tot_viewfiles != 1) {
1760 BKE_report(reports, RPT_ERROR, "Cannot pack multiview images from raw data currently...");
1761 }
1762 else if (ima->source == IMA_SRC_TILED) {
1763 BKE_report(reports, RPT_ERROR, "Cannot pack tiled images from raw data currently...");
1764 }
1765 else {
1766 ImagePackedFile *imapf = MEM_new<ImagePackedFile>(__func__);
1767 BLI_addtail(&ima->packedfiles, imapf);
1769 imapf->view = 0;
1770 imapf->tile_number = 1001;
1771 STRNCPY(imapf->filepath, ima->filepath);
1772
1773 /* The image should not be marked as "generated" since image data was provided. */
1774 ImageTile *base_tile = BKE_image_get_tile(ima, 0);
1775 base_tile->gen_flag &= ~IMA_GEN_TILE;
1776
1778 }
1779}
1780
1782 Main *bmain, Image *image, ReportList *reports, const char *data, const int data_len)
1783{
1784 if (ID_IS_LINKED(image)) {
1785 BKE_reportf(reports, RPT_ERROR, "Cannot pack linked image '%s'", image->id.name + 2);
1786 return;
1787 }
1789 BKE_report(reports, RPT_ERROR, "Cannot pack render result or viewer node images");
1790 return;
1791 }
1792 const bool is_packed = BKE_image_has_packedfile(image);
1793 const bool is_dirty = BKE_image_is_dirty(image);
1794
1795 if (is_packed && !is_dirty && !data) {
1796 /* Image is already packed and considered unmodified, do not attempt to repack it, since:
1797 * - Its original file may not be available anymore on the current FS.
1798 * - Repacking from the current runtime buffer will force the packedfile format to OpenEXR or
1799 * PNG (see code of #image_memorypack_imbuf).
1800 *
1801 * See #152638.
1802 */
1803 BKE_report(reports, RPT_INFO, "Image is already packed");
1804 return;
1805 }
1806
1808
1809 if (data) {
1810 char *data_dup = static_cast<char *>(
1811 MEM_new_array_uninitialized(size_t(data_len), 1, __func__));
1812 memcpy(data_dup, data, size_t(data_len));
1813 BKE_image_packfiles_from_mem(reports, image, data_dup, size_t(data_len));
1814 }
1815 else if (is_dirty) {
1817 }
1818 else {
1819 BKE_image_packfiles(reports, image, ID_BLEND_PATH(bmain, &image->id));
1820 }
1821}
1822
1824{
1825 uintptr_t size = 0;
1826
1827 /* viewers have memory depending on other rules, has no valid rect pointer */
1828 if (image->source == IMA_SRC_VIEWER) {
1829 return 0;
1830 }
1831
1832 std::scoped_lock lock(image->runtime->cache_mutex);
1833
1834 if (image->runtime->cache != nullptr) {
1835 ImBufCacheIter *iter = IMB_cacheIter_new(image->runtime->cache);
1836
1837 while (!IMB_cacheIter_done(iter)) {
1838 ImBuf *ibuf = IMB_cacheIter_getImBuf(iter);
1839 const ImageCacheKey *key = static_cast<const ImageCacheKey *>(
1841 IMB_cacheIter_step(iter);
1842 if (ibuf == nullptr || image_index_is_gpu_only(key->index)) {
1843 continue;
1844 }
1845
1846 size += IMB_get_size_in_memory(ibuf);
1847 }
1848 IMB_cacheIter_free(iter);
1849 }
1850
1851 return size;
1852}
1853
1855{
1856 Image *ima;
1857 uintptr_t size, totsize = 0;
1858
1859 for (ima = bmain->images.first(); ima; ima = static_cast<Image *>(ima->id.next)) {
1860 totsize += image_mem_size(ima);
1861 }
1862
1863 printf("\ntotal image memory len: %.3f MB\n", double(totsize) / double(1024 * 1024));
1864
1865 for (ima = bmain->images.first(); ima; ima = static_cast<Image *>(ima->id.next)) {
1866 size = image_mem_size(ima);
1867
1868 if (size) {
1869 printf("%s len: %.3f MB\n", ima->id.name + 2, double(size) / double(1024 * 1024));
1870 }
1871 }
1872}
1873
1874static bool imagecache_check_dirty(ImBuf *ibuf, void * /*userkey*/, void * /*userdata*/)
1875{
1876 if (ibuf == nullptr) {
1877 return false;
1878 }
1879 return (ibuf->userflags & IB_BITMAPDIRTY) == 0;
1880}
1881
1883{
1884#undef CHECK_FREED_SIZE
1885
1886 Tex *tex;
1887 Image *ima;
1888#ifdef CHECK_FREED_SIZE
1889 uintptr_t tot_freed_size = 0;
1890#endif
1891
1892 for (ima = bmain->images.first(); ima; ima = static_cast<Image *>(ima->id.next)) {
1893 ima->id.tag &= ~ID_TAG_DOIT;
1894 }
1895
1896 for (tex = bmain->textures.first(); tex; tex = static_cast<Tex *>(tex->id.next)) {
1897 if (tex->ima) {
1898 tex->ima->id.tag |= ID_TAG_DOIT;
1899 }
1900 }
1901
1902 for (ima = bmain->images.first(); ima; ima = static_cast<Image *>(ima->id.next)) {
1903 if (ima->runtime->cache && (ima->id.tag & ID_TAG_DOIT)) {
1904#ifdef CHECK_FREED_SIZE
1905 uintptr_t old_size = image_mem_size(ima);
1906#endif
1907
1908 IMB_cache_cleanup(ima->runtime->cache, imagecache_check_dirty, nullptr);
1909
1910#ifdef CHECK_FREED_SIZE
1911 tot_freed_size += old_size - image_mem_size(ima);
1912#endif
1913 }
1914 }
1915#ifdef CHECK_FREED_SIZE
1916 printf("%s: freed total %lu MB\n", __func__, tot_freed_size / (1024 * 1024));
1917#endif
1918}
1919
1920static bool imagecache_check_free_anim(ImBuf *ibuf, void *userkey, void *userdata)
1921{
1922 if (ibuf == nullptr) {
1923 return true;
1924 }
1925 const ImageCacheKey *key = static_cast<const ImageCacheKey *>(userkey);
1926 const int except_frame = *static_cast<int *>(userdata);
1927 if (image_index_is_gpu_only(key->index)) {
1928 return false;
1929 }
1930 return (ibuf->userflags & IB_BITMAPDIRTY) == 0 && key->index != IMA_NO_INDEX &&
1931 (except_frame != IMA_INDEX_ENTRY(key->index));
1932}
1933
1934void BKE_image_all_free_anim_ibufs(Main *bmain, int except_frame)
1935{
1936 Image *ima;
1937
1938 for (ima = bmain->images.first(); ima; ima = static_cast<Image *>(ima->id.next)) {
1939 if (BKE_image_is_animated(ima)) {
1940 std::scoped_lock lock(ima->runtime->cache_mutex);
1941 if (ima->runtime->cache != nullptr) {
1942 IMB_cache_cleanup(ima->runtime->cache, imagecache_check_free_anim, &except_frame);
1943 }
1944 }
1945 }
1946}
1947
1949
1950/* -------------------------------------------------------------------- */
1953
1954#define STAMP_NAME_SIZE ((MAX_ID_NAME - 2) + 16)
1955/* could allow access externally - 512 is for long names,
1956 * STAMP_NAME_SIZE is for id names, allowing them some room for description */
1959 /* TODO(sergey): Think of better size here, maybe dynamically allocated even. */
1960 char key[512];
1961 char *value;
1962 /* TODO(sergey): Support non-string values. */
1963};
1964
1966 char file[512];
1967 char note[512];
1968 char date[512];
1969 char marker[512];
1970 char time[512];
1971 char frame[512];
1972 char frame_range[512];
1979 char hostname[512];
1980
1981 /* Custom fields are used to put extra meta information header from render
1982 * engine to the result image.
1983 *
1984 * NOTE: This fields are not stamped onto the image. At least for now.
1985 */
1986 ListBaseT<StampDataCustomField> custom_fields;
1987};
1988#undef STAMP_NAME_SIZE
1989
1994static void stampdata(
1995 const Scene *scene, Object *camera, StampData *stamp_data, int do_prefix, bool use_dynamic)
1996{
1997 char text[256];
1998 tm *tl;
1999 time_t t;
2000
2001 if (scene->r.stamp & R_STAMP_FILENAME) {
2002 const char *blendfile_path = BKE_main_blendfile_path_from_global();
2003 SNPRINTF_UTF8(stamp_data->file,
2004 do_prefix ? "File %s" : "%s",
2005 (blendfile_path[0] != '\0') ? blendfile_path : "<untitled>");
2006 }
2007 else {
2008 stamp_data->file[0] = '\0';
2009 }
2010
2011 if (scene->r.stamp & R_STAMP_NOTE) {
2012 /* Never do prefix for Note */
2013 STRNCPY_UTF8(stamp_data->note, scene->r.stamp_udata);
2014 }
2015 else {
2016 stamp_data->note[0] = '\0';
2017 }
2018
2019 if (scene->r.stamp & R_STAMP_DATE) {
2020 t = time(nullptr);
2021 tl = localtime(&t);
2022 SNPRINTF_UTF8(text,
2023 "%04d/%02d/%02d %02d:%02d:%02d",
2024 tl->tm_year + 1900,
2025 tl->tm_mon + 1,
2026 tl->tm_mday,
2027 tl->tm_hour,
2028 tl->tm_min,
2029 tl->tm_sec);
2030 SNPRINTF_UTF8(stamp_data->date, do_prefix ? "Date %s" : "%s", text);
2031 }
2032 else {
2033 stamp_data->date[0] = '\0';
2034 }
2035
2036 if (use_dynamic && scene->r.stamp & R_STAMP_MARKER) {
2037 const char *name = BKE_scene_find_last_marker_name(scene, scene->r.cfra);
2038
2039 if (name) {
2040 STRNCPY_UTF8(text, name);
2041 }
2042 else {
2043 STRNCPY_UTF8(text, "<none>");
2044 }
2045
2046 SNPRINTF_UTF8(stamp_data->marker, do_prefix ? "Marker %s" : "%s", text);
2047 }
2048 else {
2049 stamp_data->marker[0] = '\0';
2050 }
2051
2052 if (use_dynamic && scene->r.stamp & R_STAMP_TIME) {
2053 const short timecode_style = USER_TIMECODE_SMPTE_FULL;
2055 sizeof(text),
2056 0,
2057 FRA2TIME(scene->r.cfra),
2058 scene->frames_per_second(),
2059 timecode_style);
2060 SNPRINTF_UTF8(stamp_data->time, do_prefix ? "Timecode %s" : "%s", text);
2061 }
2062 else {
2063 stamp_data->time[0] = '\0';
2064 }
2065
2066 if (use_dynamic && scene->r.stamp & R_STAMP_FRAME) {
2067 char fmtstr[32];
2068 int digits = 1;
2069
2070 if (scene->r.efra > 9) {
2071 digits = integer_digits_i(scene->r.efra);
2072 }
2073
2074 SNPRINTF_UTF8(fmtstr, do_prefix ? "Frame %%0%di" : "%%0%di", digits);
2075 SNPRINTF_UTF8(stamp_data->frame, fmtstr, scene->r.cfra);
2076 }
2077 else {
2078 stamp_data->frame[0] = '\0';
2079 }
2080
2081 if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
2082 SNPRINTF_UTF8(stamp_data->frame_range,
2083 do_prefix ? "Frame Range %d:%d" : "%d:%d",
2084 scene->r.sfra,
2085 scene->r.efra);
2086 }
2087 else {
2088 stamp_data->frame_range[0] = '\0';
2089 }
2090
2091 if (use_dynamic && scene->r.stamp & R_STAMP_CAMERA) {
2092 SNPRINTF_UTF8(stamp_data->camera,
2093 do_prefix ? "Camera %s" : "%s",
2094 camera ? camera->id.name + 2 : "<none>");
2095 }
2096 else {
2097 stamp_data->camera[0] = '\0';
2098 }
2099
2100 if (use_dynamic && scene->r.stamp & R_STAMP_CAMERALENS) {
2101 if (camera && camera->type == OB_CAMERA) {
2102 SNPRINTF_UTF8(text, "%.2f", ((Camera *)camera->data)->lens);
2103 }
2104 else {
2105 STRNCPY_UTF8(text, "<none>");
2106 }
2107
2108 SNPRINTF_UTF8(stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", text);
2109 }
2110 else {
2111 stamp_data->cameralens[0] = '\0';
2112 }
2113
2114 if (scene->r.stamp & R_STAMP_SCENE) {
2115 SNPRINTF_UTF8(stamp_data->scene, do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
2116 }
2117 else {
2118 stamp_data->scene[0] = '\0';
2119 }
2120
2121 if (use_dynamic && scene->r.stamp & R_STAMP_SEQSTRIP) {
2122 const Strip *strip = seq::strip_topmost_get(scene, scene->r.cfra);
2123
2124 if (strip) {
2125 STRNCPY_UTF8(text, strip->name + 2);
2126 }
2127 else {
2128 STRNCPY_UTF8(text, "<none>");
2129 }
2130
2131 SNPRINTF_UTF8(stamp_data->strip, do_prefix ? "Strip %s" : "%s", text);
2132 }
2133 else {
2134 stamp_data->strip[0] = '\0';
2135 }
2136
2137 {
2138 Render *re = RE_GetSceneRender(scene);
2139 RenderStats *stats = re ? RE_GetStats(re) : nullptr;
2140
2141 if (use_dynamic && stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
2142 BLI_timecode_string_from_time_simple(text, sizeof(text), stats->lastframetime);
2143
2144 SNPRINTF_UTF8(stamp_data->rendertime, do_prefix ? "RenderTime %s" : "%s", text);
2145 }
2146 else {
2147 stamp_data->rendertime[0] = '\0';
2148 }
2149
2150 if (use_dynamic && stats && (scene->r.stamp & R_STAMP_MEMORY)) {
2151 SNPRINTF_UTF8(stamp_data->memory, do_prefix ? "Peak Memory %dM" : "%dM", stats->mem_peak);
2152 }
2153 else {
2154 stamp_data->memory[0] = '\0';
2155 }
2156 }
2157 if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
2158 SNPRINTF_UTF8(stamp_data->frame_range,
2159 do_prefix ? "Frame Range %d:%d" : "%d:%d",
2160 scene->r.sfra,
2161 scene->r.efra);
2162 }
2163 else {
2164 stamp_data->frame_range[0] = '\0';
2165 }
2166
2167 if (scene->r.stamp & R_STAMP_HOSTNAME) {
2168 char hostname[500]; /* sizeof(stamp_data->hostname) minus some bytes for a label. */
2169 BLI_hostname_get(hostname, sizeof(hostname));
2170 SNPRINTF_UTF8(stamp_data->hostname, do_prefix ? "Hostname %s" : "%s", hostname);
2171 }
2172 else {
2173 stamp_data->hostname[0] = '\0';
2174 }
2175}
2176
2177static void stampdata_from_template(StampData *stamp_data,
2178 const Scene *scene,
2179 const StampData *stamp_data_template,
2180 bool do_prefix)
2181{
2182 if (scene->r.stamp & R_STAMP_FILENAME) {
2183 SNPRINTF_UTF8(stamp_data->file, do_prefix ? "File %s" : "%s", stamp_data_template->file);
2184 }
2185 else {
2186 stamp_data->file[0] = '\0';
2187 }
2188 if (scene->r.stamp & R_STAMP_NOTE) {
2189 STRNCPY_UTF8(stamp_data->note, stamp_data_template->note);
2190 }
2191 else {
2192 stamp_data->note[0] = '\0';
2193 }
2194 if (scene->r.stamp & R_STAMP_DATE) {
2195 SNPRINTF_UTF8(stamp_data->date, do_prefix ? "Date %s" : "%s", stamp_data_template->date);
2196 }
2197 else {
2198 stamp_data->date[0] = '\0';
2199 }
2200 if (scene->r.stamp & R_STAMP_MARKER) {
2201 SNPRINTF_UTF8(stamp_data->marker, do_prefix ? "Marker %s" : "%s", stamp_data_template->marker);
2202 }
2203 else {
2204 stamp_data->marker[0] = '\0';
2205 }
2206 if (scene->r.stamp & R_STAMP_TIME) {
2207 SNPRINTF_UTF8(stamp_data->time, do_prefix ? "Timecode %s" : "%s", stamp_data_template->time);
2208 }
2209 else {
2210 stamp_data->time[0] = '\0';
2211 }
2212 if (scene->r.stamp & R_STAMP_FRAME) {
2213 SNPRINTF_UTF8(stamp_data->frame, do_prefix ? "Frame %s" : "%s", stamp_data_template->frame);
2214 }
2215 else {
2216 stamp_data->frame[0] = '\0';
2217 }
2218 if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
2219 SNPRINTF_UTF8(stamp_data->frame_range,
2220 do_prefix ? "Frame Range %s" : "%s",
2221 stamp_data_template->frame_range);
2222 }
2223 else {
2224 stamp_data->frame_range[0] = '\0';
2225 }
2226 if (scene->r.stamp & R_STAMP_CAMERA) {
2227 SNPRINTF_UTF8(stamp_data->camera, do_prefix ? "Camera %s" : "%s", stamp_data_template->camera);
2228 }
2229 else {
2230 stamp_data->camera[0] = '\0';
2231 }
2232 if (scene->r.stamp & R_STAMP_CAMERALENS) {
2234 stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", stamp_data_template->cameralens);
2235 }
2236 else {
2237 stamp_data->cameralens[0] = '\0';
2238 }
2239 if (scene->r.stamp & R_STAMP_SCENE) {
2240 SNPRINTF_UTF8(stamp_data->scene, do_prefix ? "Scene %s" : "%s", stamp_data_template->scene);
2241 }
2242 else {
2243 stamp_data->scene[0] = '\0';
2244 }
2245 if (scene->r.stamp & R_STAMP_SEQSTRIP) {
2246 SNPRINTF_UTF8(stamp_data->strip, do_prefix ? "Strip %s" : "%s", stamp_data_template->strip);
2247 }
2248 else {
2249 stamp_data->strip[0] = '\0';
2250 }
2251 if (scene->r.stamp & R_STAMP_RENDERTIME) {
2252 SNPRINTF_UTF8(stamp_data->rendertime,
2253 do_prefix ? "RenderTime %s" : "%s",
2254 stamp_data_template->rendertime);
2255 }
2256 else {
2257 stamp_data->rendertime[0] = '\0';
2258 }
2259 if (scene->r.stamp & R_STAMP_MEMORY) {
2261 stamp_data->memory, do_prefix ? "Peak Memory %s" : "%s", stamp_data_template->memory);
2262 }
2263 else {
2264 stamp_data->memory[0] = '\0';
2265 }
2266 if (scene->r.stamp & R_STAMP_HOSTNAME) {
2268 stamp_data->hostname, do_prefix ? "Hostname %s" : "%s", stamp_data_template->hostname);
2269 }
2270 else {
2271 stamp_data->hostname[0] = '\0';
2272 }
2273}
2274
2276 Object *camera,
2277 const StampData *stamp_data_template,
2278 ImBuf *ibuf)
2279{
2280 StampData stamp_data;
2281 int w, h, pad;
2282 int x, y, y_ofs;
2283 int h_fixed;
2284 const int mono = blf_mono_font_render; /* XXX */
2285
2286 /* vars for calculating wordwrap */
2287 struct {
2288 ResultBLF info;
2289 rcti rect;
2290 } wrap;
2291
2292 /* this could be an argument if we want to operate on non linear float imbuf's
2293 * for now though this is only used for renders which use scene settings */
2294
2295#define TEXT_SIZE_CHECK(str, w, h) \
2296 ((str[0]) && ((void)(h = h_fixed), (w = int(BLF_width(mono, str, sizeof(str))))))
2297
2298 /* must enable BLF_WORD_WRAP before using */
2299#define TEXT_SIZE_CHECK_WORD_WRAP(str, w, h) \
2300 ((str[0]) && (BLF_boundbox(mono, str, sizeof(str), &wrap.rect, &wrap.info), \
2301 (void)(h = h_fixed * wrap.info.lines), \
2302 (w = BLI_rcti_size_x(&wrap.rect))))
2303
2304#define BUFF_MARGIN_X 2
2305#define BUFF_MARGIN_Y 1
2306
2307 if (!ibuf->byte_data() && !ibuf->float_data()) {
2308 return;
2309 }
2310
2311 bool do_prefix = (scene->r.stamp & R_STAMP_HIDE_LABELS) == 0;
2312 if (stamp_data_template == nullptr) {
2313 stampdata(scene, camera, &stamp_data, do_prefix, true);
2314 }
2315 else {
2316 stampdata_from_template(&stamp_data, scene, stamp_data_template, do_prefix);
2317 }
2318
2319 /* TODO: do_versions. */
2320 if (scene->r.stamp_font_id < 8) {
2321 scene->r.stamp_font_id = 12;
2322 }
2323
2324 /* set before return */
2325 BLF_size(mono, scene->r.stamp_font_id);
2326 BLF_wordwrap(mono, ibuf->x - (BUFF_MARGIN_X * 2));
2327
2328 BLF_buffer(mono,
2329 ibuf->float_data_for_write(),
2330 ibuf->byte_data_for_write(),
2331 ibuf->x,
2332 ibuf->y,
2333 4,
2334 ibuf->byte_buffer.colorspace);
2335 /* No conversion to scene linear needed, #BLF_buffer_col accepts sRGB. */
2336 BLF_buffer_col(mono, scene->r.fg_stamp);
2337 pad = BLF_width_max(mono);
2338
2339 /* use 'h_fixed' rather than 'h', aligns better */
2340 h_fixed = BLF_height_max(mono);
2341 y_ofs = -BLF_descender(mono);
2342
2343 x = 0;
2344 y = ibuf->y;
2345
2346 /* Background needs to be converted to scene linear. */
2347 float bg_stamp[4];
2349 bg_stamp[3] = scene->r.bg_stamp[3];
2350
2351 if (TEXT_SIZE_CHECK(stamp_data.file, w, h)) {
2352 /* Top left corner */
2353 y -= h;
2354
2355 /* also a little of space to the background. */
2356 IMB_rectfill_area(ibuf,
2357 bg_stamp,
2358 x - BUFF_MARGIN_X,
2359 y - BUFF_MARGIN_Y,
2360 w + BUFF_MARGIN_X,
2361 y + h + BUFF_MARGIN_Y);
2362
2363 /* and draw the text. */
2364 BLF_position(mono, x, y + y_ofs, 0.0);
2365 BLF_draw_buffer(mono, stamp_data.file, sizeof(stamp_data.file));
2366
2367 /* the extra pixel for background. */
2368 y -= BUFF_MARGIN_Y * 2;
2369 }
2370
2371 /* Top left corner, below File */
2372 if (TEXT_SIZE_CHECK(stamp_data.date, w, h)) {
2373 y -= h;
2374
2375 /* and space for background. */
2377 ibuf, bg_stamp, 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2378
2379 BLF_position(mono, x, y + y_ofs, 0.0);
2380 BLF_draw_buffer(mono, stamp_data.date, sizeof(stamp_data.date));
2381
2382 /* the extra pixel for background. */
2383 y -= BUFF_MARGIN_Y * 2;
2384 }
2385
2386 /* Top left corner, below File, Date */
2387 if (TEXT_SIZE_CHECK(stamp_data.rendertime, w, h)) {
2388 y -= h;
2389
2390 /* and space for background. */
2392 ibuf, bg_stamp, 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2393
2394 BLF_position(mono, x, y + y_ofs, 0.0);
2395 BLF_draw_buffer(mono, stamp_data.rendertime, sizeof(stamp_data.rendertime));
2396
2397 /* the extra pixel for background. */
2398 y -= BUFF_MARGIN_Y * 2;
2399 }
2400
2401 /* Top left corner, below File, Date, Render-time */
2402 if (TEXT_SIZE_CHECK(stamp_data.memory, w, h)) {
2403 y -= h;
2404
2405 /* and space for background. */
2407 ibuf, bg_stamp, 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2408
2409 BLF_position(mono, x, y + y_ofs, 0.0);
2410 BLF_draw_buffer(mono, stamp_data.memory, sizeof(stamp_data.memory));
2411
2412 /* the extra pixel for background. */
2413 y -= BUFF_MARGIN_Y * 2;
2414 }
2415
2416 /* Top left corner, below: File, Date, Render-time, Memory. */
2417 if (TEXT_SIZE_CHECK(stamp_data.hostname, w, h)) {
2418 y -= h;
2419
2420 /* and space for background. */
2422 ibuf, bg_stamp, 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2423
2424 BLF_position(mono, x, y + y_ofs, 0.0);
2425 BLF_draw_buffer(mono, stamp_data.hostname, sizeof(stamp_data.hostname));
2426
2427 /* the extra pixel for background. */
2428 y -= BUFF_MARGIN_Y * 2;
2429 }
2430
2431 /* Top left corner, below: File, Date, Memory, Render-time, Host-name. */
2433 if (TEXT_SIZE_CHECK_WORD_WRAP(stamp_data.note, w, h)) {
2434 y -= h;
2435
2436 /* and space for background. */
2438 ibuf, bg_stamp, 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2439
2440 BLF_position(mono, x, y + y_ofs + (h - h_fixed), 0.0);
2441 BLF_draw_buffer(mono, stamp_data.note, sizeof(stamp_data.note));
2442 }
2444
2445 x = 0;
2446 y = 0;
2447
2448 /* Bottom left corner, leaving space for timing */
2449 if (TEXT_SIZE_CHECK(stamp_data.marker, w, h)) {
2450
2451 /* extra space for background. */
2452 IMB_rectfill_area(ibuf,
2453 bg_stamp,
2454 x - BUFF_MARGIN_X,
2455 y - BUFF_MARGIN_Y,
2456 w + BUFF_MARGIN_X,
2457 y + h + BUFF_MARGIN_Y);
2458
2459 /* and pad the text. */
2460 BLF_position(mono, x, y + y_ofs, 0.0);
2461 BLF_draw_buffer(mono, stamp_data.marker, sizeof(stamp_data.marker));
2462
2463 /* space width. */
2464 x += w + pad;
2465 }
2466
2467 /* Left bottom corner */
2468 if (TEXT_SIZE_CHECK(stamp_data.time, w, h)) {
2469
2470 /* extra space for background */
2472 ibuf, bg_stamp, x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2473
2474 /* and pad the text. */
2475 BLF_position(mono, x, y + y_ofs, 0.0);
2476 BLF_draw_buffer(mono, stamp_data.time, sizeof(stamp_data.time));
2477
2478 /* space width. */
2479 x += w + pad;
2480 }
2481
2482 if (TEXT_SIZE_CHECK(stamp_data.frame, w, h)) {
2483
2484 /* extra space for background. */
2485 IMB_rectfill_area(ibuf,
2486 bg_stamp,
2487 x - BUFF_MARGIN_X,
2488 y - BUFF_MARGIN_Y,
2489 x + w + BUFF_MARGIN_X,
2490 y + h + BUFF_MARGIN_Y);
2491
2492 /* and pad the text. */
2493 BLF_position(mono, x, y + y_ofs, 0.0);
2494 BLF_draw_buffer(mono, stamp_data.frame, sizeof(stamp_data.frame));
2495
2496 /* space width. */
2497 x += w + pad;
2498 }
2499
2500 if (TEXT_SIZE_CHECK(stamp_data.frame_range, w, h)) {
2501
2502 /* extra space for background. */
2503 IMB_rectfill_area(ibuf,
2504 bg_stamp,
2505 x - BUFF_MARGIN_X,
2506 y - BUFF_MARGIN_Y,
2507 x + w + BUFF_MARGIN_X,
2508 y + h + BUFF_MARGIN_Y);
2509
2510 /* and pad the text. */
2511 BLF_position(mono, x, y + y_ofs, 0.0);
2512 BLF_draw_buffer(mono, stamp_data.frame_range, sizeof(stamp_data.frame_range));
2513
2514 /* space width. */
2515 x += w + pad;
2516 }
2517
2518 if (TEXT_SIZE_CHECK(stamp_data.camera, w, h)) {
2519
2520 /* extra space for background. */
2521 IMB_rectfill_area(ibuf,
2522 bg_stamp,
2523 x - BUFF_MARGIN_X,
2524 y - BUFF_MARGIN_Y,
2525 x + w + BUFF_MARGIN_X,
2526 y + h + BUFF_MARGIN_Y);
2527 BLF_position(mono, x, y + y_ofs, 0.0);
2528 BLF_draw_buffer(mono, stamp_data.camera, sizeof(stamp_data.camera));
2529
2530 /* space width. */
2531 x += w + pad;
2532 }
2533
2534 if (TEXT_SIZE_CHECK(stamp_data.cameralens, w, h)) {
2535
2536 /* extra space for background. */
2537 IMB_rectfill_area(ibuf,
2538 bg_stamp,
2539 x - BUFF_MARGIN_X,
2540 y - BUFF_MARGIN_Y,
2541 x + w + BUFF_MARGIN_X,
2542 y + h + BUFF_MARGIN_Y);
2543 BLF_position(mono, x, y + y_ofs, 0.0);
2544 BLF_draw_buffer(mono, stamp_data.cameralens, sizeof(stamp_data.cameralens));
2545 }
2546
2547 if (TEXT_SIZE_CHECK(stamp_data.scene, w, h)) {
2548
2549 /* Bottom right corner, with an extra space because the BLF API is too strict! */
2550 x = ibuf->x - w - 2;
2551
2552 /* extra space for background. */
2553 IMB_rectfill_area(ibuf,
2554 bg_stamp,
2555 x - BUFF_MARGIN_X,
2556 y - BUFF_MARGIN_Y,
2557 x + w + BUFF_MARGIN_X,
2558 y + h + BUFF_MARGIN_Y);
2559
2560 /* and pad the text. */
2561 BLF_position(mono, x, y + y_ofs, 0.0);
2562 BLF_draw_buffer(mono, stamp_data.scene, sizeof(stamp_data.scene));
2563 }
2564
2565 if (TEXT_SIZE_CHECK(stamp_data.strip, w, h)) {
2566
2567 /* Top right corner, with an extra space because the BLF API is too strict! */
2568 x = ibuf->x - w - pad;
2569 y = ibuf->y - h;
2570
2571 /* extra space for background. */
2572 IMB_rectfill_area(ibuf,
2573 bg_stamp,
2574 x - BUFF_MARGIN_X,
2575 y - BUFF_MARGIN_Y,
2576 x + w + BUFF_MARGIN_X,
2577 y + h + BUFF_MARGIN_Y);
2578
2579 BLF_position(mono, x, y + y_ofs, 0.0);
2580 BLF_draw_buffer(mono, stamp_data.strip, sizeof(stamp_data.strip));
2581 }
2582
2583 /* cleanup the buffer. */
2584 BLF_buffer(mono, nullptr, nullptr, 0, 0, 4, nullptr);
2585 BLF_wordwrap(mono, 0);
2586
2587#undef TEXT_SIZE_CHECK
2588#undef TEXT_SIZE_CHECK_WORD_WRAP
2589#undef BUFF_MARGIN_X
2590#undef BUFF_MARGIN_Y
2591}
2592
2594 Object *camera,
2595 RenderResult *rr,
2596 bool allocate_only)
2597{
2598 StampData *stamp_data;
2599
2600 if (!(scene && (scene->r.stamp & R_STAMP_ALL)) && !allocate_only) {
2601 return;
2602 }
2603
2604 if (!rr->stamp_data) {
2605 stamp_data = MEM_new_zeroed<StampData>("RenderResult.stamp_data");
2606 }
2607 else {
2608 stamp_data = rr->stamp_data;
2609 }
2610
2611 if (!allocate_only) {
2612 stampdata(scene, camera, stamp_data, 0, true);
2613 }
2614
2615 if (!rr->stamp_data) {
2616 rr->stamp_data = stamp_data;
2617 }
2618}
2619
2621{
2622 StampData *stamp_data;
2623
2624 if (!(scene && (scene->r.stamp & R_STAMP_ALL))) {
2625 return nullptr;
2626 }
2627
2628 /* Memory is allocated here (instead of by the caller) so that the caller
2629 * doesn't have to know the size of the StampData struct. */
2630 stamp_data = MEM_new_zeroed<StampData>(__func__);
2631 stampdata(scene, nullptr, stamp_data, 0, false);
2632
2633 return stamp_data;
2634}
2635
2636static const char *stamp_metadata_fields[] = {
2637 "File",
2638 "Note",
2639 "Date",
2640 "Marker",
2641 "Time",
2642 "Frame",
2643 "FrameRange",
2644 "Camera",
2645 "Lens",
2646 "Scene",
2647 "Strip",
2648 "RenderTime",
2649 "Memory",
2650 "Hostname",
2651 nullptr,
2652};
2653
2654bool BKE_stamp_is_known_field(const char *field_name)
2655{
2656 int i = 0;
2657 while (stamp_metadata_fields[i] != nullptr) {
2658 if (STREQ(field_name, stamp_metadata_fields[i])) {
2659 return true;
2660 }
2661 i++;
2662 }
2663 return false;
2664}
2665
2667 StampData *stamp_data,
2668 StampCallback callback,
2669 bool noskip)
2670{
2671 if ((callback == nullptr) || (stamp_data == nullptr)) {
2672 return;
2673 }
2674
2675#define CALL(member, value_str) \
2676 if (noskip || stamp_data->member[0]) { \
2677 callback(data, value_str, stamp_data->member, sizeof(stamp_data->member)); \
2678 } \
2679 ((void)0)
2680
2681 /* TODO(sergey): Use stamp_metadata_fields somehow, or make it more generic
2682 * meta information to avoid duplication. */
2683 CALL(file, "File");
2684 CALL(note, "Note");
2685 CALL(date, "Date");
2686 CALL(marker, "Marker");
2687 CALL(time, "Time");
2688 CALL(frame, "Frame");
2689 CALL(frame_range, "FrameRange");
2690 CALL(camera, "Camera");
2691 CALL(cameralens, "Lens");
2692 CALL(scene, "Scene");
2693 CALL(strip, "Strip");
2694 CALL(rendertime, "RenderTime");
2695 CALL(memory, "Memory");
2696 CALL(hostname, "Hostname");
2697
2698 for (StampDataCustomField &custom_field : stamp_data->custom_fields) {
2699 if (noskip || custom_field.value[0]) {
2700 callback(data, custom_field.key, custom_field.value, strlen(custom_field.value) + 1);
2701 }
2702 }
2703
2704#undef CALL
2705}
2706
2708 const Image &image,
2709 StampCallback callback,
2710 bool noskip)
2711{
2712 std::scoped_lock lock(image.runtime->cache_mutex);
2713
2714 if (!image.rr || !image.rr->stamp_data) {
2715 return;
2716 }
2717
2718 BKE_stamp_info_callback(data, image.rr->stamp_data, callback, noskip);
2719}
2720
2721void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
2722{
2723 StampData *stamp_data;
2724 if (rr->stamp_data == nullptr) {
2725 rr->stamp_data = MEM_new_zeroed<StampData>("RenderResult.stamp_data");
2726 }
2727 stamp_data = rr->stamp_data;
2729 "StampData Custom Field");
2730 STRNCPY_UTF8(field->key, key);
2731 field->value = BLI_strdup(value);
2732 BLI_addtail(&stamp_data->custom_fields, field);
2733}
2734
2736{
2737 if (stamp_data == nullptr) {
2738 return nullptr;
2739 }
2740
2741 StampData *stamp_datan = MEM_dupalloc(stamp_data);
2742 BLI_duplicatelist(&stamp_datan->custom_fields, &stamp_data->custom_fields);
2743
2744 for (StampDataCustomField &custom_fieldn : stamp_datan->custom_fields) {
2745 custom_fieldn.value = MEM_dupalloc(custom_fieldn.value);
2746 }
2747
2748 return stamp_datan;
2749}
2750
2752{
2753 if (stamp_data == nullptr) {
2754 return;
2755 }
2756 for (StampDataCustomField &custom_field : stamp_data->custom_fields) {
2757 MEM_delete(custom_field.value);
2758 }
2759 stamp_data->custom_fields.free_no_destruct();
2760 MEM_delete(stamp_data);
2761}
2762
2763/* wrap for callback only */
2764static void metadata_set_field(void *data,
2765 const char *propname,
2766 char *propvalue,
2767 int /*propvalue_maxncpy*/)
2768{
2769 /* We know it is an `ImBuf *` because that's what we pass to #BKE_stamp_info_callback. */
2770 ImBuf *imbuf = static_cast<ImBuf *>(data);
2771 IMB_metadata_set_field(imbuf->metadata_for_write(), propname, propvalue);
2772}
2773
2774static void metadata_get_field(void *data,
2775 const char *propname,
2776 char *propvalue,
2777 int propvalue_maxncpy)
2778{
2779 /* We know it is an `ImBuf *` because that's what we pass to #BKE_stamp_info_callback. */
2780 ImBuf *imbuf = static_cast<ImBuf *>(data);
2781 IMB_metadata_get_field(imbuf->metadata(), propname, propvalue, propvalue_maxncpy);
2782}
2783
2785{
2786 StampData *stamp_data = const_cast<StampData *>(rr->stamp_data);
2787 BKE_stamp_info_callback(ibuf, stamp_data, metadata_set_field, false);
2788}
2789
2790static void metadata_copy_custom_fields(const char *field, const char *value, void *rr_v)
2791{
2792 if (BKE_stamp_is_known_field(field)) {
2793 return;
2794 }
2795 RenderResult *rr = static_cast<RenderResult *>(rr_v);
2796 BKE_render_result_stamp_data(rr, field, value);
2797}
2798
2800{
2801 if (rr->stamp_data == nullptr) {
2802 rr->stamp_data = MEM_new_zeroed<StampData>("RenderResult.stamp_data");
2803 }
2804 StampData *stamp_data = rr->stamp_data;
2805 BKE_stamp_info_callback(ibuf, stamp_data, metadata_get_field, true);
2806 /* Copy render engine specific settings. */
2808}
2809
2811{
2812 if (const float *buf = ibuf->float_data()) {
2813 for (size_t tot = IMB_get_pixel_count(ibuf); tot--; buf += 4) {
2814 if (buf[3] < 1.0f) {
2815 return true;
2816 }
2817 }
2818 }
2819 else if (const uchar *buf = ibuf->byte_data()) {
2820 for (size_t tot = IMB_get_pixel_count(ibuf); tot--; buf += 4) {
2821 if (buf[3] != 255) {
2822 return true;
2823 }
2824 }
2825 }
2826
2827 return false;
2828}
2829
2830bool BKE_imbuf_write(ImBuf *ibuf, const char *filepath, const ImageFormatData *imf)
2831{
2832 if (!BLI_file_ensure_parent_dir_exists(filepath)) {
2833 CLOG_ERROR(&LOG, "Couldn't create directory for file %s: %s", filepath, std::strerror(errno));
2834 return false;
2835 }
2836
2837 BKE_image_format_to_imbuf(ibuf, imf);
2838
2839 const bool ok = IMB_save_image(ibuf, filepath, ImBufFlags::ByteData);
2840 if (!ok && errno != 0) {
2841 perror(filepath);
2842 }
2843
2844 return ok;
2845}
2846
2848 const char *filepath,
2849 const ImageFormatData *imf,
2850 const bool save_copy)
2851{
2852 const eImbFileType ftype_back = ibuf->ftype;
2853 const ImbFormatOptions foptions_back = ibuf->foptions;
2854 const ImColorMode color_mode_back = ibuf->color_mode;
2855
2856 ibuf->color_mode = imf->color_mode;
2857
2858 bool ok = BKE_imbuf_write(ibuf, filepath, imf);
2859
2860 if (save_copy) {
2861 /* note that we are not restoring _all_ settings */
2862 ibuf->color_mode = color_mode_back;
2863 ibuf->ftype = ftype_back;
2864 ibuf->foptions = foptions_back;
2865 }
2866
2867 return ok;
2868}
2869
2871 const RenderResult *rr,
2872 ImBuf *ibuf,
2873 const char *filepath,
2874 const ImageFormatData *imf)
2875{
2876 if (scene && scene->r.stamp & R_STAMP_ALL) {
2877 BKE_imbuf_stamp_info(rr, ibuf);
2878 }
2879
2880 return BKE_imbuf_write(ibuf, filepath, imf);
2881}
2882
2883MovieReader *openanim_noload(const char *filepath,
2884 const ImBufFlags flags,
2885 const int streamindex,
2886 const bool keep_original_colorspace,
2887 ColorManagedColorspaceSettings *colorspace_settings)
2888{
2889 MovieReader *anim;
2890
2891 anim = MOV_open_file(
2892 filepath, flags, streamindex, keep_original_colorspace, colorspace_settings);
2893 return anim;
2894}
2895
2896MovieReader *openanim(const char *filepath,
2897 const ImBufFlags ibuf_flags,
2898 const int streamindex,
2899 const bool keep_original_colorspace,
2900 ColorManagedColorspaceSettings *colorspace_settings)
2901{
2902 MovieReader *anim;
2903 ImBuf *ibuf;
2904
2905 anim = MOV_open_file(
2906 filepath, ibuf_flags, streamindex, keep_original_colorspace, colorspace_settings);
2907 if (anim == nullptr) {
2908 return nullptr;
2909 }
2910
2911 ibuf = MOV_decode_frame(anim, 0, IMB_PROXY_NONE);
2912 if (ibuf == nullptr) {
2913 const char *reason;
2914 if (!BLI_exists(filepath)) {
2915 reason = "file doesn't exist";
2916 }
2917 else {
2918 reason = "not an anim";
2919 }
2920 CLOG_INFO(&LOG, "unable to load anim, %s: %s", reason, filepath);
2921
2922 MOV_close(anim);
2923 return nullptr;
2924 }
2925 IMB_freeImBuf(ibuf);
2926
2927 return anim;
2928}
2929
2931
2932/* -------------------------------------------------------------------- */
2935
2936/* Notes about Image storage
2937 * - packedfile
2938 * -> written in .blend
2939 * - filename
2940 * -> written in .blend
2941 * - movie
2942 * -> comes from packedfile or filename
2943 * - renderresult
2944 * -> comes from packedfile or filename
2945 * - listbase
2946 * -> ibufs from EXR-handle.
2947 * - flip-book array
2948 * -> ibufs come from movie, temporary renderresult or sequence
2949 * - ibuf
2950 * -> comes from packedfile or filename or generated
2951 */
2952
2953Image *BKE_image_ensure_viewer(Main *bmain, int type, const char *name)
2954{
2955 Image *ima;
2956
2957 for (ima = bmain->images.first(); ima; ima = static_cast<Image *>(ima->id.next)) {
2958 if (ima->source == IMA_SRC_VIEWER) {
2959 if (ima->type == type) {
2960 break;
2961 }
2962 }
2963 }
2964
2965 if (ima == nullptr) {
2966 ima = image_alloc(bmain, std::nullopt, name, IMA_SRC_VIEWER, eImageType(type));
2967 }
2968
2969 /* Happens on reload, image-window cannot be image user when hidden. */
2970 if (ima->id.us == 0) {
2971 id_us_ensure_real(&ima->id);
2972 }
2973
2974 return ima;
2975}
2976
2977static void image_viewer_create_views(const RenderData *rd, Image *ima)
2978{
2979 if ((rd->scemode & R_MULTIVIEW) == 0) {
2980 image_add_view(ima, "", "");
2981 }
2982 else {
2983 for (SceneRenderView &srv : rd->views) {
2984 if (BKE_scene_multiview_is_render_view_active(rd, &srv) == false) {
2985 continue;
2986 }
2987 image_add_view(ima, srv.name, "");
2988 }
2989 }
2990}
2991
2992/* Returns true if the views of the given image match the actives views in the given render data.
2993 * Returns false otherwise to indicate that the image views should be recreated to make them match
2994 * the render data. */
2995static bool image_views_match_render_views(const Image *image, const RenderData *render_data)
2996{
2997 /* The number of views in the image do not match the number of active views in the render
2998 * data. */
2999 const int number_of_active_views = BKE_scene_multiview_num_views_get(render_data);
3000 if (image->views.count() != number_of_active_views) {
3001 return false;
3002 }
3003
3004 /* If the render data is not multi-view, then a single unnamed view should exist in the image,
3005 * otherwise, the views don't match. We don't have to check that a single view exist, since this
3006 * is handled by the check above for the number of views. */
3007 if (!(render_data->scemode & R_MULTIVIEW)) {
3008 const ImageView *image_view = image->views.first();
3009 /* If the view is unnamed, the views match, otherwise, they don't. */
3010 return image_view->name[0] == '\0';
3011 }
3012
3013 /* The render data is multi-view, so we need to check that for every view in the image, a
3014 * corresponding active render view with the same name exists, noting that they may not
3015 * necessarily be in the same order. */
3016 for (ImageView &image_view : image->views) {
3017 SceneRenderView *scene_render_view = static_cast<SceneRenderView *>(
3018 BLI_findstring(&render_data->views, image_view.name, offsetof(SceneRenderView, name)));
3019 /* A render view doesn't exist for that image view with the same name, so the views don't
3020 * match. */
3021 if (!scene_render_view) {
3022 return false;
3023 }
3024
3025 /* A render view exists for that image view with the same name, but it is disabled, so the
3026 * views don't match. */
3027 if (!BKE_scene_multiview_is_render_view_active(render_data, scene_render_view)) {
3028 return false;
3029 }
3030 }
3031
3032 return true;
3033}
3034
3036{
3038
3040 iuser->flag &= ~IMA_SHOW_STEREO;
3041 }
3042
3043 if (!image_views_match_render_views(ima, rd)) {
3044 std::scoped_lock lock(ima->runtime->cache_mutex);
3045
3048
3049 /* add new views */
3051 }
3052
3054}
3055
3057 bNodeTree *ntree,
3058 ID *id,
3059 void *customdata,
3060 void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
3061{
3062 switch (ntree->type) {
3063 case NTREE_SHADER:
3064 for (bNode *node : ntree->all_nodes()) {
3065 if (node->id) {
3066 if (node->type_legacy == SH_NODE_TEX_IMAGE) {
3067 NodeTexImage *tex = static_cast<NodeTexImage *>(node->storage);
3068 Image *ima = id_cast<Image *>(node->id);
3069 callback(ima, id, &tex->iuser, customdata);
3070 }
3071 if (node->type_legacy == SH_NODE_TEX_ENVIRONMENT) {
3072 NodeTexImage *tex = static_cast<NodeTexImage *>(node->storage);
3073 Image *ima = id_cast<Image *>(node->id);
3074 callback(ima, id, &tex->iuser, customdata);
3075 }
3076 }
3077 }
3078 break;
3079 case NTREE_TEXTURE:
3080 for (bNode *node : ntree->all_nodes()) {
3081 if (node->id && node->type_legacy == TEX_NODE_IMAGE) {
3082 Image *ima = id_cast<Image *>(node->id);
3083 ImageUser *iuser = static_cast<ImageUser *>(node->storage);
3084 callback(ima, id, iuser, customdata);
3085 }
3086 }
3087 break;
3088 case NTREE_COMPOSIT:
3089 for (bNode *node : ntree->all_nodes()) {
3090 if (node->id && node->type_legacy == CMP_NODE_IMAGE) {
3091 Image *ima = id_cast<Image *>(node->id);
3092 ImageUser *iuser = static_cast<ImageUser *>(node->storage);
3093 callback(ima, id, iuser, customdata);
3094 }
3095 if (node->type_legacy == CMP_NODE_CRYPTOMATTE) {
3096 CMPNodeCryptomatteSource source = static_cast<CMPNodeCryptomatteSource>(node->custom1);
3097 if (source == CMP_NODE_CRYPTOMATTE_SOURCE_IMAGE) {
3098 Image *image = id_cast<Image *>(node->id);
3099 ImageUser *image_user = &static_cast<NodeCryptomatte *>(node->storage)->iuser;
3100 callback(image, id, image_user, customdata);
3101 }
3102 }
3103 }
3104 break;
3105 case NTREE_GEOMETRY:
3106 case NTREE_CUSTOM:
3107 case NTREE_UNDEFINED:
3108 break;
3109 }
3110}
3111
3113 ID *id,
3114 ListBaseT<LinkData> *gpu_materials,
3115 void *customdata,
3116 void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
3117{
3118 for (LinkData &link : *gpu_materials) {
3119 GPUMaterial *gpu_material = static_cast<GPUMaterial *>(link.data);
3120 ListBaseT<GPUMaterialTexture> textures = GPU_material_textures(gpu_material);
3121 for (GPUMaterialTexture &gpu_material_texture : textures) {
3122 if (gpu_material_texture.iuser_available) {
3123 callback(gpu_material_texture.ima, id, &gpu_material_texture.iuser, customdata);
3124 }
3125 }
3126 }
3127}
3128
3130 ID *id,
3131 bool skip_nested_nodes,
3132 void *customdata,
3133 void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
3134{
3135 switch (GS(id->name)) {
3136 case ID_OB: {
3137 Object *ob = id_cast<Object *>(id);
3138 if (ob->empty_drawtype == OB_EMPTY_IMAGE && ob->data) {
3139 callback(id_cast<Image *>(ob->data), &ob->id, ob->iuser, customdata);
3140 }
3141 break;
3142 }
3143 case ID_MA: {
3144 Material *ma = id_cast<Material *>(id);
3145 if (ma->nodetree && !skip_nested_nodes) {
3146 image_walk_ntree_all_users(ma->nodetree, &ma->id, customdata, callback);
3147 }
3148 image_walk_gpu_materials(id, &ma->gpumaterial, customdata, callback);
3149 break;
3150 }
3151 case ID_LA: {
3152 Light *light = id_cast<Light *>(id);
3153 if (light->nodetree && !skip_nested_nodes) {
3154 image_walk_ntree_all_users(light->nodetree, &light->id, customdata, callback);
3155 }
3156 break;
3157 }
3158 case ID_WO: {
3159 World *world = id_cast<World *>(id);
3160 if (world->nodetree && !skip_nested_nodes) {
3161 image_walk_ntree_all_users(world->nodetree, &world->id, customdata, callback);
3162 }
3163 image_walk_gpu_materials(id, &world->gpumaterial, customdata, callback);
3164 break;
3165 }
3166 case ID_TE: {
3167 Tex *tex = id_cast<Tex *>(id);
3168 if (tex->type == TEX_IMAGE && tex->ima) {
3169 callback(tex->ima, &tex->id, &tex->iuser, customdata);
3170 }
3171 if (tex->nodetree && tex->use_nodes && !skip_nested_nodes) {
3172 image_walk_ntree_all_users(tex->nodetree, &tex->id, customdata, callback);
3173 }
3174 break;
3175 }
3176 case ID_NT: {
3177 bNodeTree *ntree = id_cast<bNodeTree *>(id);
3178 image_walk_ntree_all_users(ntree, &ntree->id, customdata, callback);
3179 break;
3180 }
3181 case ID_CA: {
3182 Camera *cam = id_cast<Camera *>(id);
3183 for (CameraBGImage &bgpic : cam->bg_images) {
3184 callback(bgpic.ima, nullptr, &bgpic.iuser, customdata);
3185 }
3186 break;
3187 }
3188 case ID_WM: {
3189 wmWindowManager *wm = id_cast<wmWindowManager *>(id);
3190 for (wmWindow &win : wm->windows) {
3192
3193 for (ScrArea &area : screen->areabase) {
3194 if (area.spacetype == SPACE_IMAGE) {
3195 SpaceImage *sima = area.spacedata.first_as<SpaceImage>();
3196 callback(sima->image, nullptr, &sima->iuser, customdata);
3197 }
3198 }
3199 }
3200 break;
3201 }
3202 default:
3203 break;
3204 }
3205}
3206
3208 const Main *mainp,
3209 void *customdata,
3210 void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
3211{
3212 for (Scene *scene = mainp->scenes.first(); scene; scene = static_cast<Scene *>(scene->id.next)) {
3213 image_walk_id_all_users(&scene->id, false, customdata, callback);
3214 }
3215
3216 for (Object *ob = mainp->objects.first(); ob; ob = static_cast<Object *>(ob->id.next)) {
3217 image_walk_id_all_users(&ob->id, false, customdata, callback);
3218 }
3219
3220 for (bNodeTree *ntree = mainp->nodetrees.first(); ntree;
3221 ntree = static_cast<bNodeTree *>(ntree->id.next))
3222 {
3223 image_walk_id_all_users(&ntree->id, false, customdata, callback);
3224 }
3225
3226 for (Material *ma = mainp->materials.first(); ma; ma = static_cast<Material *>(ma->id.next)) {
3227 image_walk_id_all_users(&ma->id, false, customdata, callback);
3228 }
3229
3230 for (Light *light = mainp->lights.first(); light; light = static_cast<Light *>(light->id.next)) {
3231 image_walk_id_all_users(&light->id, false, customdata, callback);
3232 }
3233
3234 for (World *world = mainp->worlds.first(); world; world = static_cast<World *>(world->id.next)) {
3235 image_walk_id_all_users(&world->id, false, customdata, callback);
3236 }
3237
3238 for (Tex *tex = mainp->textures.first(); tex; tex = static_cast<Tex *>(tex->id.next)) {
3239 image_walk_id_all_users(&tex->id, false, customdata, callback);
3240 }
3241
3242 for (Camera *cam = mainp->cameras.first(); cam; cam = static_cast<Camera *>(cam->id.next)) {
3243 image_walk_id_all_users(&cam->id, false, customdata, callback);
3244 }
3245 /* Only ever 1 `wm`. */
3246 for (wmWindowManager *wm = mainp->wm.first(); wm;
3247 wm = static_cast<wmWindowManager *>(wm->id.next))
3248 {
3249 image_walk_id_all_users(&wm->id, false, customdata, callback);
3250 }
3251}
3252
3253static void image_tag_frame_recalc(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata)
3254{
3255 Image *changed_image = static_cast<Image *>(customdata);
3256
3257 if (ima == changed_image && BKE_image_is_animated(ima)) {
3258 iuser->flag |= IMA_NEED_FRAME_RECALC;
3259
3260 if (iuser_id) {
3261 /* Must copy image user changes to evaluated data-block. */
3263 }
3264 }
3265}
3266
3267static void image_tag_reload(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata)
3268{
3269 Image *changed_image = static_cast<Image *>(customdata);
3270
3271 if (ima == changed_image) {
3272 if (iuser->scene) {
3273 image_update_views_format(ima, iuser);
3274 }
3275 if (iuser_id) {
3276 /* Must copy image user changes to evaluated data-block. */
3278 }
3279 }
3280}
3281
3283{
3284 *iuser = ImageUser{};
3285 iuser->frames = 100;
3286 iuser->sfra = 1;
3287}
3288
3290{
3291 RenderResult *rr = ima->rr;
3292
3293 iuser->multi_index = 0;
3294 iuser->layer = iuser->pass = iuser->view = 0;
3295
3296 if (rr) {
3297 BKE_image_multilayer_index(rr, iuser);
3298 }
3299}
3300
3302{
3303 /* UDIM tiles are packed into an atlas for the GPU, so need to free all. */
3305
3306 if (BKE_image_is_multiview(ima)) {
3307 const int totviews = ima->views.count();
3308 for (int i = 0; i < totviews; i++) {
3309 image_remove_ibuf(ima, i, tile->tile_number);
3310 }
3311 }
3312 else {
3313 image_remove_ibuf(ima, 0, tile->tile_number);
3314 }
3315}
3316
3318{
3319 if (ima->tiles.is_single()) {
3320 /* Can't remove the last remaining tile. */
3321 return false;
3322 }
3323
3324 image_free_tile(ima, tile);
3325 BLI_remlink(&ima->tiles, tile);
3326 MEM_delete(tile);
3327
3328 return true;
3329}
3330
3332{
3333 /* Remove all but the final tile. */
3334 while (image_remove_tile(ima, ima->tiles.last())) {
3335 ;
3336 }
3337}
3338
3339void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal)
3340{
3341 if (ima == nullptr) {
3342 return;
3343 }
3344
3345 ima->runtime->cache_mutex.lock();
3346
3347 switch (signal) {
3348 case IMA_SIGNAL_FREE:
3350
3351 if (iuser) {
3352 if (iuser->scene) {
3353 image_update_views_format(ima, iuser);
3354 }
3355 }
3356 break;
3358 if (ima->type == IMA_TYPE_UV_TEST) {
3359 if (ima->source != IMA_SRC_GENERATED) {
3360 ima->type = IMA_TYPE_IMAGE;
3361 }
3362 }
3363
3364 if (ima->source == IMA_SRC_GENERATED) {
3365 ImageTile *base_tile = BKE_image_get_tile(ima, 0);
3366 if (base_tile->gen_x == 0 || base_tile->gen_y == 0) {
3368 if (ibuf) {
3369 base_tile->gen_x = ibuf->x;
3370 base_tile->gen_y = ibuf->y;
3371 IMB_freeImBuf(ibuf);
3372 }
3373 }
3374
3375 /* Changing source type to generated will likely change file format
3376 * used by generated image buffer. Saving different file format to
3377 * the old name might confuse other applications.
3378 *
3379 * Here we ensure original image path wouldn't be used when saving
3380 * generated image.
3381 */
3382 ima->filepath[0] = '\0';
3383 }
3384
3385 if (ima->source != IMA_SRC_TILED) {
3386 /* Free all but the first tile. */
3388
3389 /* If this used to be a UDIM image, get the concrete filepath associated
3390 * with the remaining tile and use that as the new filepath. */
3391 ImageTile *base_tile = BKE_image_get_tile(ima, 0);
3392 if (BKE_image_is_filename_tokenized(ima->filepath)) {
3393 const bool was_relative = BLI_path_is_rel(ima->filepath);
3394
3395 eUDIM_TILE_FORMAT tile_format;
3396 char *udim_pattern = BKE_image_get_tile_strformat(ima->filepath, &tile_format);
3398 ima->filepath, udim_pattern, tile_format, base_tile->tile_number);
3399 MEM_delete(udim_pattern);
3400
3401 if (was_relative) {
3402 const char *relbase = ID_BLEND_PATH(bmain, &ima->id);
3403 BLI_path_rel(ima->filepath, relbase);
3404 }
3405 }
3406
3407 /* If the remaining tile was not number 1001, we need to reassign it so that
3408 * ibuf lookups from the cache still succeed. */
3409 base_tile->tile_number = 1001;
3410 }
3411 else {
3412 /* When changing to UDIM, attempt to tokenize the filepath. */
3413 BKE_image_ensure_tile_token(ima->filepath, sizeof(ima->filepath));
3414 }
3415
3416 /* image buffers for non-sequence multilayer will share buffers with RenderResult,
3417 * however sequence multilayer will own buffers. Such logic makes switching from
3418 * single multilayer file to sequence completely unstable
3419 * since changes in nodes seems this workaround isn't needed anymore, all sockets
3420 * are nicely detecting anyway, but freeing buffers always here makes multilayer
3421 * sequences behave stable
3422 */
3424
3425 if (iuser) {
3426 image_tag_frame_recalc(ima, nullptr, iuser, ima);
3427 }
3429
3430 break;
3431
3432 case IMA_SIGNAL_RELOAD:
3433 /* try to repack file */
3434 if (BKE_image_has_packedfile(ima)) {
3435 const int tot_viewfiles = image_num_viewfiles(ima);
3436 const int tot_files = tot_viewfiles * ima->tiles.count();
3437
3438 if (!BLI_listbase_count_is_equal_to(&ima->packedfiles, tot_files)) {
3439 /* in case there are new available files to be loaded */
3441 BKE_image_packfiles(nullptr, ima, ID_BLEND_PATH(bmain, &ima->id));
3442 }
3443 else {
3444 for (ImagePackedFile &imapf : ima->packedfiles) {
3445 PackedFile *pf;
3446 pf = BKE_packedfile_new(nullptr, imapf.filepath, ID_BLEND_PATH(bmain, &ima->id));
3447 if (pf) {
3449 imapf.packedfile = pf;
3450 }
3451 else {
3452 printf("ERROR: Image \"%s\" not available. Keeping packed image\n", imapf.filepath);
3453 }
3454 }
3455 }
3456
3457 if (BKE_image_has_packedfile(ima)) {
3459 }
3460 }
3461 else {
3463 }
3464
3465 if (ima->source == IMA_SRC_TILED) {
3466 ListBaseT<LinkData> new_tiles = {nullptr, nullptr};
3467 int new_start, new_range;
3468
3469 char filepath[FILE_MAX];
3470 STRNCPY(filepath, ima->filepath);
3471 BLI_path_abs(filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
3472 bool result = BKE_image_get_tile_info(filepath, &new_tiles, &new_start, &new_range);
3473 if (result) {
3474 /* Because the prior and new list of tiles are both sparse sequences, we need to be sure
3475 * to account for how the two sets might or might not overlap. To be complete, we start
3476 * the refresh process by clearing all existing tiles, stopping when there's only 1 tile
3477 * left. */
3479
3480 ImageTile *base_tile = BKE_image_get_tile(ima, 0);
3481 int remaining_tile_number = base_tile->tile_number;
3482 bool needs_final_cleanup = true;
3483
3484 /* Add in all the new tiles. As the image is proven to be on disk at this point, remove
3485 * the generation flag from the remaining tile in case this was previously a generated
3486 * image. */
3487 base_tile->gen_flag &= ~IMA_GEN_TILE;
3488 for (LinkData &new_tile : new_tiles) {
3489 int new_tile_number = POINTER_AS_INT(new_tile.data);
3490 BKE_image_add_tile(ima, new_tile_number, nullptr);
3491 if (new_tile_number == remaining_tile_number) {
3492 needs_final_cleanup = false;
3493 }
3494 }
3495
3496 /* Final cleanup if the prior remaining tile was never encountered in the new list. */
3497 if (needs_final_cleanup) {
3498 BKE_image_remove_tile(ima, BKE_image_get_tile(ima, remaining_tile_number));
3499 }
3500 }
3501 new_tiles.free_no_destruct();
3502 }
3503 else if (ima->filepath[0] != '\0') {
3504 /* If the filepath is set at this point remove the generation flag. */
3505 ImageTile *base_tile = BKE_image_get_tile(ima, 0);
3506 base_tile->gen_flag &= ~IMA_GEN_TILE;
3507 }
3508
3509 if (iuser) {
3510 image_tag_reload(ima, nullptr, iuser, ima);
3511 }
3513 break;
3515 if (iuser) {
3516 if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
3517 if (ima->type == IMA_TYPE_MULTILAYER) {
3518 BKE_image_init_imageuser(ima, iuser);
3519 }
3520 }
3521 }
3522 break;
3525 break;
3526 }
3527
3528 /* NOTE: It is important that the image is unlocked before calling the node tree updates since
3529 * its update functions might need to acquire image buffers from this image. */
3530 ima->runtime->cache_mutex.unlock();
3531
3532 BKE_ntree_update_tag_id_changed(bmain, &ima->id);
3533 BKE_ntree_update(*bmain);
3534}
3535
3541 const int pass,
3542 const int view,
3543 int *r_passindex)
3544{
3545 RenderPass *rpass_ret = nullptr;
3546 RenderPass *rpass;
3547
3548 int rp_index = 0;
3549 const char *rp_name = "";
3550
3551 for (rpass = rl->passes.first(); rpass; rpass = rpass->next, rp_index++) {
3552 if (rp_index == pass) {
3553 rpass_ret = rpass;
3554 if (view == 0) {
3555 /* no multiview or left eye */
3556 break;
3557 }
3558
3559 rp_name = rpass->name;
3560 }
3561 /* multiview */
3562 else if (rp_name[0] && STREQ(rpass->name, rp_name) && (rpass->view_id == view)) {
3563 rpass_ret = rpass;
3564 break;
3565 }
3566 }
3567
3568 /* fall back to the first pass in the layer */
3569 if (rpass_ret == nullptr) {
3570 rp_index = 0;
3571 rpass_ret = rl->passes.first();
3572 }
3573
3574 if (r_passindex) {
3575 *r_passindex = (rpass == rpass_ret ? rp_index : pass);
3576 }
3577
3578 return rpass_ret;
3579}
3580
3582 const ImageTile *tile,
3583 char *label,
3584 const int label_maxncpy)
3585{
3586 label[0] = '\0';
3587 if (ima == nullptr || tile == nullptr) {
3588 return 0;
3589 }
3590
3591 if (tile->label[0]) {
3592 return BLI_strncpy_rlen(label, tile->label, label_maxncpy);
3593 }
3594 return BLI_snprintf_rlen(label, label_maxncpy, "%d", tile->tile_number);
3595}
3596
3597bool BKE_image_get_tile_info(char *filepath,
3598 ListBaseT<LinkData> *tiles,
3599 int *r_tile_start,
3600 int *r_tile_range)
3601{
3603 BLI_path_split_dir_file(filepath, dirname, sizeof(dirname), filename, sizeof(filename));
3604
3607 }
3608
3609 eUDIM_TILE_FORMAT tile_format;
3610 char *udim_pattern = BKE_image_get_tile_strformat(filename, &tile_format);
3611
3612 bool all_valid_udim = true;
3613 int min_udim = IMA_UDIM_MAX + 1;
3614 int max_udim = 0;
3615 int id;
3616
3617 direntry *dirs;
3618 const uint dirs_num = BLI_filelist_dir_contents(dirname, &dirs);
3619 for (int i = 0; i < dirs_num; i++) {
3620 if (!(dirs[i].type & S_IFREG)) {
3621 continue;
3622 }
3623
3624 if (!BKE_image_get_tile_number_from_filepath(dirs[i].relname, udim_pattern, tile_format, &id))
3625 {
3626 continue;
3627 }
3628
3629 if (id < 1001 || id > IMA_UDIM_MAX) {
3630 all_valid_udim = false;
3631 break;
3632 }
3633
3635 min_udim = min_ii(min_udim, id);
3636 max_udim = max_ii(max_udim, id);
3637 }
3638 BLI_filelist_free(dirs, dirs_num);
3639 MEM_SAFE_DELETE(udim_pattern);
3640
3641 if (all_valid_udim && min_udim <= IMA_UDIM_MAX) {
3643
3644 *r_tile_start = min_udim;
3645 *r_tile_range = max_udim - min_udim + 1;
3646 return true;
3647 }
3648 return false;
3649}
3650
3651ImageTile *BKE_image_add_tile(Image *ima, int tile_number, const char *label)
3652{
3653 if (ima->source != IMA_SRC_TILED) {
3654 return nullptr;
3655 }
3656
3657 if (tile_number < 1001 || tile_number > IMA_UDIM_MAX) {
3658 return nullptr;
3659 }
3660
3661 /* Search the first tile that has a higher number.
3662 * We then insert before that to keep the list sorted. */
3663 ImageTile *next_tile;
3664 for (next_tile = ima->tiles.first(); next_tile; next_tile = next_tile->next) {
3665 if (next_tile->tile_number == tile_number) {
3666 /* Tile already exists. */
3667 return nullptr;
3668 }
3669 if (next_tile->tile_number > tile_number) {
3670 break;
3671 }
3672 }
3673
3674 ImageTile *tile = imagetile_alloc(tile_number);
3675
3676 if (next_tile) {
3677 BLI_insertlinkbefore(&ima->tiles, next_tile, tile);
3678 }
3679 else {
3680 BLI_addtail(&ima->tiles, tile);
3681 }
3682
3683 if (label) {
3684 STRNCPY_UTF8(tile->label, label);
3685 }
3686
3688
3689 return tile;
3690}
3691
3693{
3694 if (ima == nullptr || tile == nullptr || ima->source != IMA_SRC_TILED) {
3695 return false;
3696 }
3697
3698 return image_remove_tile(ima, tile);
3699}
3700
3701void BKE_image_reassign_tile(Image *ima, ImageTile *tile, int new_tile_number)
3702{
3703 if (ima == nullptr || tile == nullptr || ima->source != IMA_SRC_TILED) {
3704 return;
3705 }
3706
3707 if (new_tile_number < 1001 || new_tile_number > IMA_UDIM_MAX) {
3708 return;
3709 }
3710
3711 const int old_tile_number = tile->tile_number;
3712 tile->tile_number = new_tile_number;
3713
3714 if (BKE_image_is_multiview(ima)) {
3715 const int totviews = ima->views.count();
3716 for (int i = 0; i < totviews; i++) {
3717 ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, i, old_tile_number, nullptr);
3718 image_remove_ibuf(ima, i, old_tile_number);
3719 image_assign_ibuf(ima, ibuf, i, new_tile_number);
3720 IMB_freeImBuf(ibuf);
3721 }
3722 }
3723 else {
3724 ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, 0, old_tile_number, nullptr);
3725 image_remove_ibuf(ima, 0, old_tile_number);
3726 image_assign_ibuf(ima, ibuf, 0, new_tile_number);
3727 IMB_freeImBuf(ibuf);
3728 }
3729
3731}
3732
3733static int tile_sort_cb(const void *a, const void *b)
3734{
3735 const ImageTile *tile_a = static_cast<const ImageTile *>(a);
3736 const ImageTile *tile_b = static_cast<const ImageTile *>(b);
3737 return (tile_a->tile_number > tile_b->tile_number) ? 1 : 0;
3738}
3739
3741{
3742 if (ima == nullptr || ima->source != IMA_SRC_TILED) {
3743 return;
3744 }
3745
3746 BLI_listbase_sort(&ima->tiles, tile_sort_cb);
3747}
3748
3750{
3751 if (ima == nullptr || tile == nullptr || ima->source != IMA_SRC_TILED) {
3752 return false;
3753 }
3754
3755 image_free_tile(ima, tile);
3756
3757 ImBuf *tile_ibuf = add_ibuf_for_tile(ima, tile);
3758
3759 if (tile_ibuf != nullptr) {
3760 image_assign_ibuf(ima, tile_ibuf, 0, tile->tile_number);
3761 BKE_image_release_ibuf(ima, tile_ibuf, nullptr);
3762 return true;
3763 }
3764 return false;
3765}
3766
3768{
3769 const char *filename = BLI_path_basename(filepath);
3770 return strstr(filename, "<UDIM>") != nullptr || strstr(filename, "<UVTILE>") != nullptr;
3771}
3772
3773void BKE_image_ensure_tile_token_filename_only(char *filename, size_t filename_maxncpy)
3774{
3776 "Only the file-name component should be used!");
3777
3779 return;
3780 }
3781
3782 std::string path(filename);
3783 std::smatch match;
3784
3785 /* General 4-digit "udim" pattern. As this format is susceptible to ambiguity
3786 * with other digit sequences, we can leverage the supported range of roughly
3787 * 1000 through 2000 to provide better detection. */
3788 std::regex pattern(R"((.*[._-])([12]\d{3})([._-].*))");
3789 if (std::regex_search(path, match, pattern)) {
3790 BLI_strncpy(filename, match.format("$1<UDIM>$3").c_str(), filename_maxncpy);
3791 return;
3792 }
3793
3794 /* General `u##_v###` `uvtile` pattern. */
3795 pattern = std::regex(R"((.*)(u\d{1,2}_v\d{1,3})(\D.*))");
3796 if (std::regex_search(path, match, pattern)) {
3797 BLI_strncpy(filename, match.format("$1<UVTILE>$3").c_str(), filename_maxncpy);
3798 return;
3799 }
3800}
3801
3802void BKE_image_ensure_tile_token(char *filepath, size_t filepath_maxncpy)
3803{
3804 char *filename = const_cast<char *>(BLI_path_basename(filepath));
3805 BKE_image_ensure_tile_token_filename_only(filename, filepath_maxncpy - (filename - filepath));
3806}
3807
3808bool BKE_image_tile_filepath_exists(const char *filepath)
3809{
3810 BLI_assert(!BLI_path_is_rel(filepath));
3811
3812 char dirname[FILE_MAXDIR];
3813 BLI_path_split_dir_part(filepath, dirname, sizeof(dirname));
3814
3815 eUDIM_TILE_FORMAT tile_format;
3816 char *udim_pattern = BKE_image_get_tile_strformat(filepath, &tile_format);
3817
3818 bool found = false;
3819 direntry *dirs;
3820 const uint dirs_num = BLI_filelist_dir_contents(dirname, &dirs);
3821 for (int i = 0; i < dirs_num; i++) {
3822 if (!(dirs[i].type & S_IFREG)) {
3823 continue;
3824 }
3825
3826 int id;
3827 if (!BKE_image_get_tile_number_from_filepath(dirs[i].path, udim_pattern, tile_format, &id)) {
3828 continue;
3829 }
3830
3831 if (id < 1001 || id > IMA_UDIM_MAX) {
3832 continue;
3833 }
3834
3835 found = true;
3836 break;
3837 }
3838 BLI_filelist_free(dirs, dirs_num);
3839 MEM_SAFE_DELETE(udim_pattern);
3840
3841 return found;
3842}
3843
3844char *BKE_image_get_tile_strformat(const char *filepath, eUDIM_TILE_FORMAT *r_tile_format)
3845{
3846 if (filepath == nullptr || r_tile_format == nullptr) {
3847 return nullptr;
3848 }
3849
3850 if (strstr(filepath, "<UDIM>") != nullptr) {
3851 *r_tile_format = UDIM_TILE_FORMAT_UDIM;
3852 return BLI_string_replaceN(filepath, "<UDIM>", "%d");
3853 }
3854 if (strstr(filepath, "<UVTILE>") != nullptr) {
3855 *r_tile_format = UDIM_TILE_FORMAT_UVTILE;
3856 return BLI_string_replaceN(filepath, "<UVTILE>", "u%d_v%d");
3857 }
3858
3859 *r_tile_format = UDIM_TILE_FORMAT_NONE;
3860 return nullptr;
3861}
3862
3864 const char *pattern,
3865 eUDIM_TILE_FORMAT tile_format,
3866 int *r_tile_number)
3867{
3868 if (filepath == nullptr || pattern == nullptr || r_tile_number == nullptr) {
3869 return false;
3870 }
3871
3872 int u, v;
3873 bool result = false;
3874
3875 if (tile_format == UDIM_TILE_FORMAT_UDIM) {
3876 if (sscanf(filepath, pattern, &u) == 1) {
3877 *r_tile_number = u;
3878 result = true;
3879 }
3880 }
3881 else if (tile_format == UDIM_TILE_FORMAT_UVTILE) {
3882 if (sscanf(filepath, pattern, &u, &v) == 2) {
3883 *r_tile_number = 1001 + (u - 1) + ((v - 1) * 10);
3884 result = true;
3885 }
3886 }
3887
3888 return result;
3889}
3890
3892 const char *pattern,
3893 eUDIM_TILE_FORMAT tile_format,
3894 int tile_number)
3895{
3896 if (filepath == nullptr || pattern == nullptr) {
3897 return;
3898 }
3899
3900 if (tile_format == UDIM_TILE_FORMAT_UDIM) {
3901 BLI_snprintf(filepath, FILE_MAX, pattern, tile_number);
3902 }
3903 else if (tile_format == UDIM_TILE_FORMAT_UVTILE) {
3904 int u = ((tile_number - 1001) % 10);
3905 int v = ((tile_number - 1001) / 10);
3906 BLI_snprintf(filepath, FILE_MAX, pattern, u + 1, v + 1);
3907 }
3908}
3909
3911{
3912 /* If layer or pass changes, we need an index for the imbufs list. */
3913 /* NOTE: it is called for rendered results, but it doesn't use the index! */
3914
3915 RenderLayer *rl;
3916 RenderPass *rpass = nullptr;
3917
3918 if (rr == nullptr) {
3919 return nullptr;
3920 }
3921
3922 if (iuser) {
3923 short index = 0, rv_index, rl_index = 0;
3924 bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr);
3925
3926 rv_index = is_stereo ? iuser->multiview_eye : iuser->view;
3927 if (RE_HasCombinedLayer(rr)) {
3928 rl_index += 1;
3929 }
3930
3931 for (rl = rr->layers.first(); rl; rl = rl->next, rl_index++) {
3932 if (iuser->layer == rl_index) {
3933 int rp_index;
3934 rpass = image_render_pass_get(rl, iuser->pass, rv_index, &rp_index);
3935 iuser->multi_index = index + rp_index;
3936 break;
3937 }
3938
3939 index += rl->passes.count();
3940 }
3941 }
3942
3943 return rpass;
3944}
3945
3947{
3948 if (iuser) {
3949 bool is_stereo = BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO);
3950 if (is_stereo) {
3951 iuser->multi_index = iuser->multiview_eye;
3952 }
3953 else {
3954 if ((iuser->view < 0) ||
3955 (iuser->view >= BLI_listbase_count_at_most(&ima->views, iuser->view + 1)))
3956 {
3957 iuser->multi_index = iuser->view = 0;
3958 }
3959 else {
3960 iuser->multi_index = iuser->view;
3961 }
3962 }
3963 }
3964}
3965
3967{
3968 /* If layer or pass changes, we need an index for the imbufs list. */
3969 /* NOTE: it is called for rendered results, but it doesn't use the index! */
3970
3971 if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
3972 if (ima->type == IMA_TYPE_MULTILAYER) {
3973 return true;
3974 }
3975 }
3976 else if (ima->source == IMA_SRC_VIEWER) {
3977 if (ima->type == IMA_TYPE_R_RESULT) {
3978 return true;
3979 }
3980 }
3981 return false;
3982}
3983
3985{
3986 ImageView *view = ima->views.first();
3987 return (view && (view->next || view->name[0]));
3988}
3989
3991{
3992 return BKE_image_is_multiview(ima) &&
3993 (BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) &&
3994 BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
3995}
3996
3998{
3999 /* update image views from render views, but only if they actually changed,
4000 * to avoid invalid memory access during render. ideally these should always
4001 * be acquired with a mutex along with the render result, but there are still
4002 * some places with just an image pointer that need to access views */
4003 if (rr && ima->views.count() == rr->views.count()) {
4004 ImageView *iv = ima->views.first();
4005 RenderView *rv = rr->views.first();
4006 bool modified = false;
4007 for (; rv; rv = rv->next, iv = iv->next) {
4008 modified |= !STREQ(rv->name, iv->name);
4009 }
4010 if (!modified) {
4011 return;
4012 }
4013 }
4014
4016
4017 if (rr) {
4018 for (RenderView &rv : rr->views) {
4019 ImageView *iv = MEM_new<ImageView>("Viewer Image View");
4020 STRNCPY_UTF8(iv->name, rv.name);
4021 BLI_addtail(&ima->views, iv);
4022 }
4023 }
4024}
4025
4027{
4028 std::scoped_lock lock(ima->runtime->cache_mutex);
4029
4030 RenderResult *rr = nullptr;
4031
4032 if (ima->rr) {
4033 rr = ima->rr;
4034 }
4035 else if (scene && ima->type == IMA_TYPE_R_RESULT) {
4036 if (ima->render_slot == ima->last_render_slot) {
4038 }
4039 else {
4040 rr = BKE_image_get_renderslot(ima, ima->render_slot)->render;
4041 }
4042
4043 /* set proper views */
4045 }
4046
4047 if (rr) {
4049 }
4050
4051 return rr;
4052}
4053
4054void BKE_image_release_renderresult(Scene *scene, Image *ima, RenderResult *render_result)
4055{
4056 if (render_result) {
4057 /* Decrement user counter, and free if nobody else holds a reference to the result. */
4058 std::scoped_lock lock(ima->runtime->cache_mutex);
4059 RE_FreeRenderResult(render_result);
4060 }
4061
4062 if (ima->rr) {
4063 /* pass */
4064 }
4065 else if (scene && ima->type == IMA_TYPE_R_RESULT) {
4066 if (ima->render_slot == ima->last_render_slot) {
4068 }
4069 }
4070}
4071
4073{
4074 if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
4075 return BLI_path_extension_check(ima->filepath, ".exr");
4076 }
4077 return false;
4078}
4079
4080void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
4081{
4082 /* called right before rendering, ima->renderslots contains render
4083 * result pointers for everything but the current render */
4084 Render *re = RE_GetSceneRender(scene);
4085
4086 /* Ensure we always have a valid render slot. */
4087 if (!ima->renderslots.first()) {
4088 BKE_image_add_renderslot(ima, nullptr);
4089 ima->render_slot = 0;
4090 ima->last_render_slot = 0;
4091 }
4092 else if (ima->render_slot >= ima->renderslots.count()) {
4093 ima->render_slot = 0;
4094 ima->last_render_slot = 0;
4095 }
4096
4097 RenderSlot *last_slot = BKE_image_get_renderslot(ima, ima->last_render_slot);
4098 RenderSlot *cur_slot = BKE_image_get_renderslot(ima, ima->render_slot);
4099
4100 if (last_slot && ima->render_slot != ima->last_render_slot) {
4101 last_slot->render = nullptr;
4102 RE_SwapResult(re, &last_slot->render);
4103
4104 if (cur_slot->render) {
4105 if (free_current_slot) {
4106 BKE_image_clear_renderslot(ima, nullptr, ima->render_slot);
4107 }
4108 else {
4109 RE_SwapResult(re, &cur_slot->render);
4110 }
4111 }
4112 }
4113
4114 ima->last_render_slot = ima->render_slot;
4115}
4116
4118
4119/* -------------------------------------------------------------------- */
4122
4123static void image_add_view(Image *ima, const char *viewname, const char *filepath)
4124{
4125 ImageView *iv = MEM_new<ImageView>("Viewer Image View");
4126 STRNCPY_UTF8(iv->name, viewname);
4127 STRNCPY(iv->filepath, filepath);
4128
4129 /* For stereo drawing we need to ensure:
4130 * STEREO_LEFT_NAME == STEREO_LEFT_ID and
4131 * STEREO_RIGHT_NAME == STEREO_RIGHT_ID */
4132
4133 if (STREQ(viewname, STEREO_LEFT_NAME)) {
4134 BLI_addhead(&ima->views, iv);
4135 }
4136 else if (STREQ(viewname, STEREO_RIGHT_NAME)) {
4137 ImageView *left_iv = static_cast<ImageView *>(
4138 BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)));
4139
4140 if (left_iv == nullptr) {
4141 BLI_addhead(&ima->views, iv);
4142 }
4143 else {
4144 BLI_insertlinkafter(&ima->views, left_iv, iv);
4145 }
4146 }
4147 else {
4148 BLI_addtail(&ima->views, iv);
4149 }
4150}
4151
4152/* After imbuf load, OpenEXR type can return with a EXR-handle open
4153 * in that case we have to build a render-result. */
4154static void image_create_multilayer(Image *ima, ImBuf *ibuf, ExrReadHandle *handle, int framenr)
4155{
4156 const char *colorspace = ima->colorspace_settings.name;
4157 bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);
4158
4159 /* only load rr once for multiview */
4160 if (!ima->rr) {
4161 ima->rr = RE_MultilayerConvert(handle, colorspace, predivide, ibuf->x, ibuf->y);
4162 }
4163
4164 IMB_exr_close(handle);
4165
4166 if (ima->rr != nullptr) {
4167 ima->rr->framenr = framenr;
4168 BKE_stamp_info_from_imbuf(ima->rr, ibuf);
4169 }
4170
4171 /* set proper views */
4172 image_init_multilayer_multiview(ima, ima->rr);
4173}
4174
4176static void image_init_after_load(Image *ima, ImageUser *iuser, ImBuf * /*ibuf*/)
4177{
4178 /* Preview is null when it has never been used as an icon before.
4179 * Never handle previews/icons outside of main thread. */
4180 if (G.background == 0 && ima->preview == nullptr && BLI_thread_is_main()) {
4182 }
4183
4185 /* Images should never get loaded if the corresponding tile does not exist,
4186 * but we should at least not crash if it happens due to a bug elsewhere. */
4187 BLI_assert(tile != nullptr);
4189}
4190
4192{
4193 switch (ima->alpha_mode) {
4194 case IMA_ALPHA_STRAIGHT:
4195 return ImBufFlags::Zero;
4196 case IMA_ALPHA_PREMUL:
4200 case IMA_ALPHA_IGNORE:
4202 }
4203
4204 return ImBufFlags::Zero;
4205}
4206
4211{
4212 const bool is_multiview = BKE_image_is_multiview(ima);
4213
4214 if (!is_multiview) {
4215 return 1;
4216 }
4217 if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
4218 return 1;
4219 }
4220 /* R_IMF_VIEWS_INDIVIDUAL */
4221
4222 return ima->views.count();
4223}
4224
4225static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int entry, int frame)
4226{
4227 ImBuf *ibuf = nullptr;
4228
4229 /* either we load from RenderResult, or we have to load a new one */
4230
4231 /* check for new RenderResult */
4232 if (ima->rr == nullptr || frame != ima->rr->framenr) {
4233 if (ima->rr) {
4234 /* Cached image buffers shares pointers with render result,
4235 * need to ensure there's no image buffers are hanging around
4236 * with dead links after freeing the render result.
4237 */
4239 RE_FreeRenderResult(ima->rr);
4240 ima->rr = nullptr;
4241 }
4242
4243 ibuf = image_load_image_file(ima, iuser, entry, frame, true);
4244
4245 if (ibuf) { /* actually an error */
4246 ima->type = IMA_TYPE_IMAGE;
4247 printf("error, multi is normal image\n");
4248 }
4249 }
4250 if (ima->rr) {
4251 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
4252
4253 if (rpass && rpass->ibuf) {
4254 ibuf = rpass->ibuf;
4255 IMB_refImBuf(ibuf);
4256
4257 BKE_imbuf_stamp_info(ima->rr, ibuf);
4258 copy_v2_v2_db(ibuf->ppm, ima->rr->ppm);
4259
4260 image_init_after_load(ima, iuser, ibuf);
4261 ibuf->fileframe = frame;
4262 image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, entry);
4263 }
4264 else if (rpass == nullptr && iuser) {
4266 }
4267 }
4268
4269 /* Cache null to indicate failed load. */
4270 if (ibuf == nullptr && (ima->rr == nullptr || iuser)) {
4271 image_assign_ibuf(ima, nullptr, iuser ? iuser->multi_index : 0, entry);
4272 }
4273
4274 return ibuf;
4275}
4276
4277static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const int view_id)
4278{
4279 ImBuf *ibuf = nullptr;
4280 ImageAnim *ia;
4281
4282 ia = static_cast<ImageAnim *>(BLI_findlink(&ima->anims, view_id));
4283
4284 if (ia->anim == nullptr) {
4285 char filepath[FILE_MAX];
4287 ImageUser iuser_t{};
4288
4289 if (iuser) {
4290 iuser_t = *iuser;
4291 }
4292
4293 iuser_t.view = view_id;
4294
4295 BKE_image_user_file_path(&iuser_t, ima, filepath);
4296
4297 /* FIXME: make several stream accessible in image editor, too. */
4298 ia->anim = openanim(filepath, flags, 0, false, &ima->colorspace_settings);
4299
4300 /* let's initialize this user */
4301 if (ia->anim && iuser && iuser->frames == 0) {
4302 iuser->frames = MOV_get_duration_frames(ia->anim);
4303 }
4304 }
4305
4306 if (ia->anim) {
4307 int dur = MOV_get_duration_frames(ia->anim);
4308 int fra = frame - 1;
4309
4310 fra = std::max(fra, 0);
4311 fra = std::min(fra, dur - 1);
4313
4314 if (ibuf) {
4315 image_init_after_load(ima, iuser, ibuf);
4316 }
4317 }
4318
4319 return ibuf;
4320}
4321
4322static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
4323{
4324 ImBuf *ibuf = nullptr;
4325 const bool is_multiview = BKE_image_is_multiview(ima);
4326 const int tot_viewfiles = image_num_viewfiles(ima);
4327
4328 if (!BLI_listbase_count_is_equal_to(&ima->anims, tot_viewfiles)) {
4329 image_free_anims(ima);
4330
4331 for (int i = 0; i < tot_viewfiles; i++) {
4332 /* allocate the ImageAnim */
4333 ImageAnim *ia = MEM_new<ImageAnim>("Image Anim");
4334 BLI_addtail(&ima->anims, ia);
4335 }
4336 }
4337
4338 if (!is_multiview) {
4339 ibuf = load_movie_single(ima, iuser, frame, 0);
4340 image_assign_ibuf(ima, ibuf, 0, frame);
4341 }
4342 else {
4343 const int totviews = ima->views.count();
4344 Array<ImBuf *> ibuf_arr(totviews);
4345
4346 for (int i = 0; i < tot_viewfiles; i++) {
4347 ibuf_arr[i] = load_movie_single(ima, iuser, frame, i);
4348 }
4349
4350 if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D) {
4351 IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], ibuf_arr.data(), &ibuf_arr[1]);
4352 }
4353
4354 for (int i = 0; i < totviews; i++) {
4355 image_assign_ibuf(ima, ibuf_arr[i], i, frame);
4356 }
4357
4358 /* return the original requested ImBuf */
4359 ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)];
4360
4361 /* "remove" the others (decrease their refcount) */
4362 for (int i = 0; i < totviews; i++) {
4363 if (ibuf_arr[i] != ibuf) {
4364 IMB_freeImBuf(ibuf_arr[i]);
4365 }
4366 }
4367 }
4368
4369 return ibuf;
4370}
4371
4373 ImageUser *iuser,
4374 int cfra,
4375 const int view_id,
4376 const bool has_packed,
4377 const bool is_sequence,
4378 bool *r_cache_ibuf)
4379{
4380 char filepath[FILE_MAX];
4381 ImBuf *ibuf = nullptr;
4382 ExrReadHandle *exr_handle = nullptr;
4385
4386 *r_cache_ibuf = true;
4387 const int tile_number = image_get_tile_number_from_iuser(ima, iuser);
4388
4389 /* is there a PackedFile with this image ? */
4390 if (has_packed && !is_sequence) {
4391 for (ImagePackedFile &imapf : ima->packedfiles) {
4392 if (imapf.view == view_id && imapf.tile_number == tile_number) {
4393 if (imapf.packedfile) {
4394 uchar *data = static_cast<uchar *>(const_cast<void *>(imapf.packedfile->data));
4396 imapf.packedfile->size,
4397 flag,
4398 "<packed data>",
4399 nullptr,
4400 &ima->colorspace_settings);
4401 if (ibuf && flag_is_set(ibuf->flags, ImBufFlags::MultiLayer)) {
4403 }
4404 }
4405 break;
4406 }
4407 }
4408 }
4409 else {
4410 if (is_sequence) {
4411 ima->lastframe = cfra;
4412 }
4413
4414 /* get the correct filepath */
4415 const bool is_tiled = (ima->source == IMA_SRC_TILED);
4416 if (!(is_sequence || is_tiled)) {
4417 BKE_image_user_frame_calc(ima, iuser, cfra);
4418 }
4419
4420 ImageUser iuser_t{};
4421 if (iuser) {
4422 iuser_t = *iuser;
4423 }
4424 else {
4425 iuser_t.framenr = ima->lastframe;
4426 }
4427
4428 iuser_t.view = view_id;
4429
4430 BKE_image_user_file_path(&iuser_t, ima, filepath);
4431
4432 /* read ibuf */
4433 ibuf = IMB_load_image_from_filepath(filepath, flag, &ima->colorspace_settings);
4434 if (ibuf && flag_is_set(ibuf->flags, ImBufFlags::MultiLayer)) {
4435 exr_handle = IMB_exr_open_multilayer(filepath);
4436 }
4437 }
4438
4439 if (ibuf) {
4440 if (flag_is_set(ibuf->flags, ImBufFlags::MultiLayer)) {
4441 /* Handle multilayer and multiview cases, don't assign ibuf here. will be set layer
4442 * in BKE_image_acquire_ibuf from ima->rr. The loaded ibuf only contains metadata,
4443 * so it is discarded here. */
4444 if (exr_handle) {
4445 image_create_multilayer(ima, ibuf, exr_handle, cfra);
4446 ima->type = IMA_TYPE_MULTILAYER;
4447 }
4448 IMB_freeImBuf(ibuf);
4449 ibuf = nullptr;
4450 /* Null ibuf in the cache means the image failed to load. However for multilayer we load
4451 * pixels into RenderResult instead and intentionally leave ibuf null. */
4452 *r_cache_ibuf = false;
4453 }
4454 else {
4455 image_init_after_load(ima, iuser, ibuf);
4456
4457 /* Remember which frame this sequence buffer holds, for per-frame cache management. */
4458 if (is_sequence) {
4459 ibuf->fileframe = cfra;
4460 }
4461
4462 /* Make packed file for auto-pack. */
4463 if (!is_sequence && (has_packed == false) && (G.fileflags & G_FILE_AUTOPACK)) {
4464 ImagePackedFile *imapf = MEM_new<ImagePackedFile>("Image Pack-file");
4465 BLI_addtail(&ima->packedfiles, imapf);
4466
4467 STRNCPY(imapf->filepath, filepath);
4468 imapf->view = view_id;
4469 imapf->tile_number = tile_number;
4471 nullptr, filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
4472
4474 }
4475 }
4476 }
4477
4478 return ibuf;
4479}
4480
4481/* warning, 'iuser' can be null
4482 * NOTE: Image->views was already populated (in image_update_views_format)
4483 */
4485 Image *ima, ImageUser *iuser, int entry, int cfra, bool is_sequence)
4486{
4487 ImBuf *ibuf = nullptr;
4488 const bool is_multiview = BKE_image_is_multiview(ima);
4489 const bool is_tiled = (ima->source == IMA_SRC_TILED);
4490 const int tot_viewfiles = image_num_viewfiles(ima);
4491 bool has_packed = BKE_image_has_packedfile(ima);
4492
4493 if (!(is_sequence || is_tiled)) {
4494 /* ensure clean ima */
4496 }
4497
4498 /* this should never happen, but just playing safe */
4499 if (!is_sequence && has_packed) {
4500 const int totfiles = tot_viewfiles * ima->tiles.count();
4501 if (!BLI_listbase_count_is_equal_to(&ima->packedfiles, totfiles)) {
4503 has_packed = false;
4504 }
4505 }
4506
4507 if (!is_multiview) {
4508 bool put_in_cache;
4509 ibuf = load_image_single(ima, iuser, cfra, 0, has_packed, is_sequence, &put_in_cache);
4510 if (put_in_cache) {
4511 const int index = (is_sequence || is_tiled) ? 0 : IMA_NO_INDEX;
4512 image_assign_ibuf(ima, ibuf, index, entry);
4513 }
4514 }
4515 else {
4516 const int totviews = ima->views.count();
4517 BLI_assert(totviews > 0);
4518
4519 Array<ImBuf *> ibuf_arr(totviews);
4520 Array<bool> cache_ibuf_arr(totviews);
4521
4522 for (int i = 0; i < tot_viewfiles; i++) {
4523 ibuf_arr[i] = load_image_single(
4524 ima, iuser, cfra, i, has_packed, is_sequence, &cache_ibuf_arr[i]);
4525 }
4526
4527 /* multi-views/multi-layers OpenEXR files directly populate ima, and return null ibuf... */
4528 if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D && ibuf_arr[0] &&
4529 tot_viewfiles == 1 && totviews >= 2)
4530 {
4531 IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], ibuf_arr.data(), &ibuf_arr[1]);
4532 }
4533
4534 /* return the original requested ImBuf */
4535 const int ibuf_index = (iuser && iuser->multi_index < totviews) ? iuser->multi_index : 0;
4536 ibuf = ibuf_arr[ibuf_index];
4537
4538 for (int i = 0; i < totviews; i++) {
4539 if (cache_ibuf_arr[i]) {
4540 image_assign_ibuf(ima, ibuf_arr[i], i, entry);
4541 }
4542 }
4543
4544 /* "remove" the others (decrease their refcount) */
4545 for (int i = 0; i < totviews; i++) {
4546 if (ibuf_arr[i] != ibuf) {
4547 IMB_freeImBuf(ibuf_arr[i]);
4548 }
4549 }
4550 }
4551
4552 return ibuf;
4553}
4554
4556{
4557 const bool is_multilayer = BKE_image_is_multilayer(ima);
4558 const bool is_backdrop = (ima->source == IMA_SRC_VIEWER) && (ima->type == IMA_TYPE_COMPOSITE) &&
4559 (iuser == nullptr);
4561
4562 if (is_multilayer) {
4563 return iuser ? iuser->multi_index : index;
4564 }
4565 if (is_backdrop) {
4566 if (BKE_image_is_stereo(ima)) {
4567 /* Backdrop hack / workaround (since there is no `iuser`). */
4568 return ima->eye;
4569 }
4570 }
4571 else if (BKE_image_is_multiview(ima)) {
4572 return iuser ? iuser->multi_index : index;
4573 }
4574
4575 return index;
4576}
4577
4579{
4580 if (!(ima->flag & IMA_AUTOSAVE_TEMPPACK)) {
4581 const int count = BLI_listbase_count(&ima->autosave_packedfiles);
4582 if (count != 0) {
4583 /* Logically, this shouldn't happen but avoid returning early and leaving the file in an
4584 * invalid state if we encounter this situation. */
4585 CLOG_ERROR(
4586 &LOG,
4587 "Image (%s) has %d autosaved files but no `IMA_AUTOSAVE_TEMPPACK` flag! Restoring flag.",
4588 ima->id.name,
4589 count);
4590 ima->flag |= IMA_AUTOSAVE_TEMPPACK;
4591 }
4592 else {
4593 return;
4594 }
4595 }
4596
4597 std::scoped_lock lock(ima->runtime->cache_mutex);
4598
4599 const bool tiled = ima->source == IMA_SRC_TILED;
4600 const int index = image_get_multiview_index(ima, nullptr);
4601
4604 for (ImagePackedFile &imapf : ima->autosave_packedfiles) {
4605 if (imapf.packedfile) {
4606 const int entry = tiled ? imapf.tile_number : 0;
4607
4609 static_cast<uchar *>(const_cast<void *>(imapf.packedfile->data)),
4610 imapf.packedfile->size,
4611 flag,
4612 "<packed data>",
4613 nullptr,
4614 &ima->colorspace_settings);
4615 if (ibuf) {
4616 ibuf->userflags |= IB_BITMAPDIRTY;
4617 image_assign_ibuf(ima, ibuf, index, entry);
4618 IMB_freeImBuf(ibuf);
4619 }
4620 }
4621 }
4622
4624}
4625
4627{
4628 ImBuf *ibuf = nullptr;
4629
4630 if (ima->rr == nullptr) {
4631 ibuf = image_load_image_file(ima, iuser, 0, 0, false);
4632 if (ibuf) { /* actually an error */
4633 ima->type = IMA_TYPE_IMAGE;
4634 return ibuf;
4635 }
4636 }
4637 if (ima->rr) {
4638 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
4639
4640 if (rpass && rpass->ibuf) {
4641 ibuf = rpass->ibuf;
4642 IMB_refImBuf(ibuf);
4643
4644 image_init_after_load(ima, iuser, ibuf);
4645
4646 BKE_imbuf_stamp_info(ima->rr, ibuf);
4647 copy_v2_v2_db(ibuf->ppm, ima->rr->ppm);
4648
4649 image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
4650 }
4651 else if (rpass == nullptr && iuser) {
4653 }
4654 }
4655
4656 /* Cache null to indicate failed load. A failed file load applies to all passes. */
4657 if (ibuf == nullptr && ima->rr == nullptr) {
4658 image_assign_ibuf(ima, nullptr, IMA_NO_INDEX, 0);
4659 }
4660 else if (ibuf == nullptr && iuser) {
4661 image_assign_ibuf(ima, nullptr, iuser->multi_index, 0);
4662 }
4663
4664 return ibuf;
4665}
4666
4667/* showing RGBA result itself (from compo/sequence) or
4668 * like exr, using layers etc */
4669/* always returns a single ibuf, also during render progress */
4670static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_lock)
4671{
4672 RenderView *rv;
4673 ImBuf *pass_ibuf = nullptr;
4674 float dither;
4675 const int from_render = (ima->render_slot == ima->last_render_slot);
4676
4677 if (!(iuser && iuser->scene)) {
4678 return nullptr;
4679 }
4680
4681 /* if we the caller is not going to release the lock, don't give the image */
4682 if (!r_lock) {
4683 return nullptr;
4684 }
4685
4686 Render *re = RE_GetSceneRender(iuser->scene);
4687
4688 const int layer = iuser->layer;
4689 const int pass = iuser->pass;
4690 int actview = iuser->view;
4691
4692 if (BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO)) {
4693 actview = iuser->multiview_eye;
4694 }
4695
4696 RenderResult rres{};
4697 RenderSlot *slot;
4698 if (from_render) {
4699 RE_AcquireResultImage(re, &rres, actview);
4700 }
4701 else if ((slot = BKE_image_get_renderslot(ima, ima->render_slot))->render) {
4702 rres = *(slot->render);
4703 rres.have_combined = (rres.views.first())->ibuf != nullptr;
4704 }
4705
4706 if (!(rres.rectx > 0 && rres.recty > 0)) {
4707 if (from_render) {
4709 }
4710 return nullptr;
4711 }
4712
4713 /* release is done in BKE_image_release_ibuf using r_lock */
4714 if (from_render) {
4716 *r_lock = re;
4717 rv = nullptr;
4718 }
4719 else {
4720 rv = static_cast<RenderView *>(BLI_findlink(&rres.views, actview));
4721 if (rv == nullptr) {
4722 rv = rres.views.first();
4723 }
4724 }
4725
4726 /* this gives active layer, composite or sequence result */
4727 if (rv == nullptr) {
4728 pass_ibuf = rres.ibuf;
4729 }
4730 else {
4731 pass_ibuf = rv->ibuf;
4732 }
4733
4734 dither = iuser->scene->r.dither_intensity;
4735
4736 /* combined layer gets added as first layer */
4737 if (rres.have_combined && layer == 0) {
4738 /* pass */
4739 }
4740 else if (pass_ibuf && pass_ibuf->byte_data() && layer == 0) {
4741 /* pass */
4742 }
4743 else if (rres.layers.first()) {
4744 RenderLayer *rl = static_cast<RenderLayer *>(
4745 BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0)));
4746 if (rl) {
4747 RenderPass *rpass = image_render_pass_get(rl, pass, actview, nullptr);
4748 if (rpass) {
4749 pass_ibuf = rpass->ibuf;
4750 if (pass != 0) {
4751 dither = 0.0f; /* don't dither passes */
4752 }
4753 }
4754 }
4755 }
4756
4757 /* Put an empty image buffer to the cache. This allows to achieve the following:
4758 *
4759 * 1. It makes it so the generic logic in the #BKE_image_has_loaded_ibuf properly detects that
4760 * an Image used to display render result has loaded image buffer.
4761 *
4762 * Surely there are all the design questions about scene-dependent Render Result image
4763 * data-block, and the behavior of the flag dependent on whether the Render Result image was ever
4764 * shown on screen. The purpose of this code is to preserve the Python API behavior to the level
4765 * prior to the #RenderResult refactor to use #ImBuf which happened for Blender 4.0.
4766 *
4767 * 2. Provides an image buffer which can be used to communicate the render resolution (with
4768 * possible border render applied to it) prior to the actual pixels storage is allocated. */
4769 if (ima->runtime->cache == nullptr) {
4770 ImBuf *empty_ibuf = IMB_allocImBuf(0, 0, ImBufFlags::Zero);
4771 image_assign_ibuf(ima, empty_ibuf, IMA_NO_INDEX, 0);
4772
4773 /* The cache references the image buffer, and the freeing only happens if the buffer has 0
4774 * references at the time when the #IMB_freeImBuf() is called. This particular image buffer is
4775 * to be freed together with the cache, without any extra reference counting done by any image
4776 * pixel accessor. */
4777 IMB_freeImBuf(empty_ibuf);
4778 }
4779
4780 if (pass_ibuf) {
4781 /* TODO(@sergey): Perhaps its better to assign dither when #ImBuf is allocated for the render
4782 * result. It will avoid modification here, and allow comparing render results with different
4783 * dither applied to them. */
4784 pass_ibuf->dither = dither;
4785
4786 IMB_refImBuf(pass_ibuf);
4787 }
4788 else {
4789 pass_ibuf = image_get_cached_ibuf_for_index_entry(ima, IMA_NO_INDEX, 0, nullptr);
4790
4791 /* Assign the current render resolution to the image buffer.
4792 * The actual storage is still empty. The intended use is to merely communicate the actual
4793 * render resolution prior to render border is "un-cropped". */
4794 pass_ibuf->x = rres.rectx;
4795 pass_ibuf->y = rres.recty;
4796 }
4797
4798 return pass_ibuf;
4799}
4800
4801static void image_get_entry_and_index(Image *ima, ImageUser *iuser, int *r_entry, int *r_index)
4802{
4803 int frame = 0, index = image_get_multiview_index(ima, iuser);
4804
4805 /* see if we already have an appropriate ibuf, with image source and type */
4806 if (ima->source == IMA_SRC_MOVIE) {
4807 frame = iuser ? iuser->framenr : ima->lastframe;
4808 }
4809 else if (ima->source == IMA_SRC_SEQUENCE) {
4810 if (ima->type == IMA_TYPE_IMAGE) {
4811 frame = iuser ? iuser->framenr : ima->lastframe;
4812 }
4813 else if (ima->type == IMA_TYPE_MULTILAYER) {
4814 frame = iuser ? iuser->framenr : ima->lastframe;
4815 }
4816 }
4817 else if (ima->source == IMA_SRC_TILED) {
4818 frame = image_get_tile_number_from_iuser(ima, iuser);
4819 }
4820
4821 *r_entry = frame;
4822 *r_index = index;
4823}
4824
4825/* Get the ibuf from an image cache for a given image user.
4826 *
4827 * Returns referenced image buffer if it exists, callee is to
4828 * call IMB_freeImBuf to de-reference the image buffer after
4829 * it's done handling it.
4830 */
4832 Image *ima, ImageUser *iuser, int *r_entry, int *r_index, bool *r_is_cached_empty)
4833{
4834 ImBuf *ibuf = nullptr;
4835 int entry = 0, index = image_get_multiview_index(ima, iuser);
4836
4837 /* see if we already have an appropriate ibuf, with image source and type */
4838 if (ima->source == IMA_SRC_MOVIE) {
4839 entry = iuser ? iuser->framenr : ima->lastframe;
4840 ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, r_is_cached_empty);
4841 ima->lastframe = entry;
4842 }
4843 else if (ima->source == IMA_SRC_SEQUENCE) {
4844 if (ima->type == IMA_TYPE_IMAGE) {
4845 entry = iuser ? iuser->framenr : ima->lastframe;
4846 ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, r_is_cached_empty);
4847 ima->lastframe = entry;
4848 }
4849 else if (ima->type == IMA_TYPE_MULTILAYER) {
4850 entry = iuser ? iuser->framenr : ima->lastframe;
4851 ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, r_is_cached_empty);
4852 }
4853 }
4854 else if (ima->source == IMA_SRC_FILE) {
4855 if (ima->type == IMA_TYPE_IMAGE) {
4856 ibuf = image_get_cached_ibuf_for_index_entry(ima, index, 0, r_is_cached_empty);
4857 }
4858 else if (ima->type == IMA_TYPE_MULTILAYER) {
4860 ima, ima->rr ? index : IMA_NO_INDEX, 0, r_is_cached_empty);
4861 }
4862 }
4863 else if (ima->source == IMA_SRC_GENERATED) {
4864 ibuf = image_get_cached_ibuf_for_index_entry(ima, index, 0, r_is_cached_empty);
4865 }
4866 else if (ima->source == IMA_SRC_VIEWER) {
4867 /* always verify entirely, not that this shouldn't happen
4868 * as part of texture sampling in rendering anyway, so not
4869 * a big bottleneck */
4870 }
4871 else if (ima->source == IMA_SRC_TILED) {
4872 if (ELEM(ima->type, IMA_TYPE_IMAGE, IMA_TYPE_MULTILAYER)) {
4873 entry = image_get_tile_number_from_iuser(ima, iuser);
4874 ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, r_is_cached_empty);
4875 }
4876 }
4877
4878 if (r_entry) {
4879 *r_entry = entry;
4880 }
4881
4882 if (r_index) {
4883 *r_index = index;
4884 }
4885
4886 return ibuf;
4887}
4888
4890{
4891 if (ima == nullptr) {
4892 return false;
4893 }
4894
4896 if (tile == nullptr) {
4897 return false;
4898 }
4899
4900 return true;
4901}
4902
4910 ImageUser *iuser,
4911 void **r_lock,
4912 const bool ensure_host_buffer,
4913 bool *r_load_failed,
4914 const bool cached_only)
4915{
4916 ImBuf *ibuf = nullptr;
4917 int entry = 0, index = 0;
4918
4919 if (r_lock) {
4920 *r_lock = nullptr;
4921 }
4922 if (r_load_failed) {
4923 *r_load_failed = false;
4924 }
4925
4926 /* quick reject tests */
4927 if (!image_quick_test(ima, iuser)) {
4928 return nullptr;
4929 }
4930
4931 bool is_cached_empty = false;
4932 ibuf = image_get_cached_ibuf(ima, iuser, &entry, &index, &is_cached_empty);
4933 if (is_cached_empty) {
4934 if (r_load_failed) {
4935 *r_load_failed = true;
4936 }
4937 return nullptr;
4938 }
4939
4940 if (ibuf == nullptr && cached_only) {
4941 /* Don't load from file. */
4942 return nullptr;
4943 }
4944
4945 if (ibuf == nullptr) {
4946 /* We are sure we have to load the ibuf, using source and type. */
4947 if (ima->source == IMA_SRC_MOVIE) {
4948 /* Source is from single file, use flip-book to store ibuf. */
4949 ibuf = image_load_movie_file(ima, iuser, entry);
4950 }
4951 else if (ima->source == IMA_SRC_SEQUENCE) {
4952 if (ima->type == IMA_TYPE_IMAGE) {
4953 /* Regular files, ibufs in flip-book, allows saving. */
4954 ibuf = image_load_image_file(ima, iuser, entry, entry, true);
4955 }
4956 /* no else; on load the ima type can change */
4957 if (ima->type == IMA_TYPE_MULTILAYER) {
4958 /* Only 1 layer/pass stored in imbufs, no EXR-handle anim storage, no saving. */
4959 ibuf = image_load_sequence_multilayer(ima, iuser, entry, entry);
4960 }
4961 }
4962 else if (ima->source == IMA_SRC_TILED) {
4963 /* Nothing was cached. Check to see if the tile should be generated. */
4964 ImageTile *tile = BKE_image_get_tile(ima, entry);
4965 if ((tile->gen_flag & IMA_GEN_TILE) != 0) {
4966 ibuf = add_ibuf_for_tile(ima, tile);
4967 image_assign_ibuf(ima, ibuf, 0, entry);
4968 }
4969 else {
4970 if (ima->type == IMA_TYPE_IMAGE) {
4971 /* Regular files, ibufs in flip-book, allows saving */
4972 ibuf = image_load_image_file(ima, iuser, entry, 0, false);
4973 }
4974 /* no else; on load the ima type can change */
4975 if (ima->type == IMA_TYPE_MULTILAYER) {
4976 /* Only 1 layer/pass stored in imbufs, no EXR-handle anim storage, no saving. */
4977 ibuf = image_load_sequence_multilayer(ima, iuser, entry, 0);
4978 }
4979 }
4980 }
4981 else if (ima->source == IMA_SRC_FILE) {
4982
4983 if (ima->type == IMA_TYPE_IMAGE) {
4984 ibuf = image_load_image_file(
4985 ima, iuser, 0, entry, false); /* cfra only for '#', this global is OK */
4986 }
4987 /* no else; on load the ima type can change */
4988 if (ima->type == IMA_TYPE_MULTILAYER) {
4989 /* keeps render result, stores ibufs in listbase, allows saving */
4990 ibuf = image_get_ibuf_multilayer(ima, iuser);
4991 }
4992 }
4993 else if (ima->source == IMA_SRC_GENERATED) {
4994 /* Generated is: `ibuf` is allocated dynamically. */
4995 /* UV test-grid or black or solid etc. */
4996 ImageTile *base_tile = BKE_image_get_tile(ima, 0);
4997 if (base_tile->gen_x == 0) {
4998 base_tile->gen_x = 1024;
4999 }
5000 if (base_tile->gen_y == 0) {
5001 base_tile->gen_y = 1024;
5002 }
5003 if (base_tile->gen_depth == 0) {
5004 base_tile->gen_depth = 24;
5005 }
5006 ibuf = add_ibuf_for_tile(ima, base_tile);
5007 image_assign_ibuf(ima, ibuf, index, 0);
5008 }
5009 else if (ima->source == IMA_SRC_VIEWER) {
5010 if (ima->type == IMA_TYPE_R_RESULT) {
5011 /* always verify entirely, and potentially
5012 * returns pointer to release later */
5013 ibuf = image_get_render_result(ima, iuser, r_lock);
5014 }
5015 else if (ima->type == IMA_TYPE_COMPOSITE) {
5016 /* requires lock/unlock, otherwise don't return image */
5017 if (r_lock) {
5018 /* unlock in BKE_image_release_ibuf */
5020 *r_lock = ima;
5021
5022 /* XXX anim play for viewer nodes not yet supported */
5023 entry = 0; // XXX iuser ? iuser->framenr : 0;
5024 ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, nullptr);
5025
5026 if (!ibuf) {
5027 /* Composite Viewer, all handled in compositor */
5028 /* fake ibuf, will be filled in compositor */
5030 image_assign_ibuf(ima, ibuf, index, entry);
5031 }
5032 }
5033 }
5034 }
5035
5036 /* We only want movies and sequences to be memory limited. */
5037 if (ibuf != nullptr && !ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
5038 ibuf->userflags |= IB_PERSISTENT;
5039 }
5040 }
5041
5042 if (ensure_host_buffer) {
5044 }
5045
5046 return ibuf;
5047}
5048
5049ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
5050{
5051 /* NOTE: same as #image_acquire_ibuf, but can be used to retrieve images being rendered in
5052 * a thread safe way, always call both acquire and release. */
5053
5054 if (ima == nullptr) {
5055 return nullptr;
5056 }
5057
5058 std::scoped_lock lock(ima->runtime->cache_mutex);
5059 return image_acquire_ibuf(ima, iuser, r_lock, true);
5060}
5061
5062/* Identical to BKE_image_acquire_ibuf but passing false to the ensure_host_buffer argument for the
5063 * image_acquire_ibuf function. */
5065 Image *ima, ImageUser *iuser, void **r_lock, bool *r_load_failed, const bool cached_only)
5066{
5067 if (ima == nullptr) {
5068 return nullptr;
5069 }
5070
5071 std::scoped_lock lock(ima->runtime->cache_mutex);
5072 return image_acquire_ibuf(ima, iuser, r_lock, false, r_load_failed, cached_only);
5073}
5074
5076 const ImageUser &image_user,
5077 const char *view_name)
5078{
5079 if (BLI_listbase_count_at_most(&image.rr->views, 2) <= 1) {
5080 return 0;
5081 }
5082
5083 const int view_image = image_user.view;
5084 const bool is_allview = (view_image == 0); /* if view selected == All (0) */
5085
5086 if (is_allview) {
5087 /* Heuristic to match image name with scene names check if the view name exists in the image.
5088 */
5089 const int view = BLI_findstringindex(&image.rr->views, view_name, offsetof(RenderView, name));
5090 if (view == -1) {
5091 return 0;
5092 }
5093 return view;
5094 }
5095
5096 return view_image - 1;
5097}
5098
5100 Image &image,
5101 const ImageUser &image_user,
5102 const char *pass_name,
5103 const char *view_name)
5104{
5105 std::scoped_lock lock(image.runtime->cache_mutex);
5106
5107 /* Local changes to the original ImageUser. */
5108 ImageUser local_user = image_user;
5109
5110 /* Force load the image once, possibly with a different user from what it will need to be in the
5111 * end. This ensures proper image type, and initializes multi-layer state when needed. */
5112 ImBuf *tmp_ibuf = image_acquire_ibuf(&image, &local_user, nullptr, false);
5113 IMB_freeImBuf(tmp_ibuf);
5114
5116 BLI_assert(pass_name);
5117
5118 if (!image.rr) {
5119 return nullptr;
5120 }
5121
5122 const RenderLayer *render_layer = static_cast<const RenderLayer *>(
5123 BLI_findlink(&image.rr->layers, local_user.layer));
5124
5125 local_user.view = get_multilayer_view_index(image, local_user, view_name);
5126 local_user.pass = BLI_findstringindex(
5127 &render_layer->passes, pass_name, offsetof(RenderPass, name));
5128
5129 if (!BKE_image_multilayer_index(image.rr, &local_user)) {
5130 return nullptr;
5131 }
5132 }
5133 else {
5134 local_user.multi_index = BKE_scene_multiview_view_id_get(&render_data, view_name);
5135 }
5136
5137 return image_acquire_ibuf(&image, &local_user, nullptr, true);
5138}
5139
5140void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
5141{
5142 if (lock != nullptr) {
5143 /* for getting image during threaded render / compositing, need to release */
5144 if (lock == ima) {
5145 BLI_thread_unlock(LOCK_VIEWER); /* viewer image */
5146 }
5147 else {
5148 RE_ReleaseResultImage(static_cast<Render *>(lock)); /* render result */
5149 BLI_thread_unlock(LOCK_VIEWER); /* view image imbuf */
5150 }
5151 }
5152
5153 if (ibuf) {
5154 std::scoped_lock lock(ima->runtime->cache_mutex);
5155 IMB_freeImBuf(ibuf);
5156 }
5157}
5158
5160{
5161 ImBuf *ibuf;
5162
5163 /* quick reject tests */
5164 if (!image_quick_test(ima, iuser)) {
5165 return false;
5166 }
5167
5168 std::scoped_lock lock(ima->runtime->cache_mutex);
5169
5170 ibuf = image_get_cached_ibuf(ima, iuser, nullptr, nullptr, nullptr);
5171
5172 if (!ibuf) {
5173 ibuf = image_acquire_ibuf(ima, iuser, nullptr, false);
5174 }
5175
5176 IMB_freeImBuf(ibuf);
5177
5178 return ibuf != nullptr;
5179}
5180
5181ImBuf *BKE_image_preview(Image *ima, const short max_size, short *r_width, short *r_height)
5182{
5183 void *lock;
5184 ImBuf *image_ibuf = BKE_image_acquire_ibuf(ima, nullptr, &lock);
5185 if (image_ibuf == nullptr) {
5186 return nullptr;
5187 }
5188
5189 ImBuf *preview = IMB_dupImBuf(image_ibuf);
5190 float scale = float(max_size) / float(std::max(image_ibuf->x, image_ibuf->y));
5191 if (r_width) {
5192 *r_width = image_ibuf->x;
5193 }
5194 if (r_height) {
5195 *r_height = image_ibuf->y;
5196 }
5197 BKE_image_release_ibuf(ima, image_ibuf, lock);
5198
5199 /* Resize. */
5200 IMB_scale(preview, scale * image_ibuf->x, scale * image_ibuf->y, IMBScaleFilter::Box, false);
5201 IMB_byte_from_float(preview);
5202
5203 return preview;
5204}
5205
5207
5208/* -------------------------------------------------------------------- */
5211
5219
5221 ListBaseT<ImagePoolItem> image_buffers = {};
5224};
5225
5227{
5228 ImagePool *pool = MEM_new<ImagePool>(__func__);
5230 return pool;
5231}
5232
5234{
5235 /* Use single lock to dereference all the image buffers. */
5236 {
5237 std::scoped_lock lock(pool->mutex);
5238 for (ImagePoolItem *item = pool->image_buffers.first(); item != nullptr; item = item->next) {
5239 if (item->ibuf != nullptr) {
5240 std::scoped_lock lock(item->image->runtime->cache_mutex);
5241 IMB_freeImBuf(item->ibuf);
5242 }
5243 }
5244
5246 }
5247 MEM_delete(pool);
5248}
5249
5251 ImagePool *pool, Image *image, int entry, int index, bool *r_found)
5252{
5253 for (ImagePoolItem &item : pool->image_buffers) {
5254 if (item.image == image && item.entry == entry && item.index == index) {
5255 *r_found = true;
5256 return item.ibuf;
5257 }
5258 }
5259
5260 *r_found = false;
5261 return nullptr;
5262}
5263
5265{
5266 ImBuf *ibuf;
5267 int index, entry;
5268 bool found;
5269
5270 if (!image_quick_test(ima, iuser)) {
5271 return nullptr;
5272 }
5273
5274 if (pool == nullptr) {
5275 /* Pool could be null, in this case use general acquire function. */
5276 return BKE_image_acquire_ibuf(ima, iuser, nullptr);
5277 }
5278
5279 image_get_entry_and_index(ima, iuser, &entry, &index);
5280
5281 /* Use double-checked locking, to avoid locking when the requested image buffer is already in the
5282 * pool. */
5283
5284 ibuf = image_pool_find_item(pool, ima, entry, index, &found);
5285 if (found) {
5286 return ibuf;
5287 }
5288
5289 /* Lock the pool, to allow thread-safe modification of the content of the pool. */
5290 std::scoped_lock lock(pool->mutex);
5291
5292 ibuf = image_pool_find_item(pool, ima, entry, index, &found);
5293
5294 /* Will also create item even in cases image buffer failed to load,
5295 * prevents trying to load the same buggy file multiple times. */
5296 if (!found) {
5297 ImagePoolItem *item;
5298
5299 /* Thread-safe acquisition of an image buffer from the image.
5300 * The acquisition does not use image pools, so there is no risk of recursive or out-of-order
5301 * mutex locking. */
5302 ibuf = BKE_image_acquire_ibuf(ima, iuser, nullptr);
5303
5304 item = static_cast<ImagePoolItem *>(BLI_mempool_alloc(pool->memory_pool));
5305 item->image = ima;
5306 item->entry = entry;
5307 item->index = index;
5308 item->ibuf = ibuf;
5309
5310 BLI_addtail(&pool->image_buffers, item);
5311 }
5312
5313 return ibuf;
5314}
5315
5317{
5318 /* if pool wasn't actually used, use general release stuff,
5319 * for pools image buffers will be dereferenced on pool free
5320 */
5321 if (pool == nullptr) {
5322 BKE_image_release_ibuf(ima, ibuf, nullptr);
5323 }
5324}
5325
5327{
5328 return a.frames == b.frames && a.offset == b.offset && a.sfra == b.sfra && a.cycl == b.cycl &&
5329 a.multi_index == b.multi_index && a.view == b.view && a.layer == b.layer &&
5330 a.pass == b.pass && a.tile == b.tile;
5331}
5332
5333int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, bool *r_is_in_range)
5334{
5335 const int len = iuser->frames;
5336
5337 if (r_is_in_range) {
5338 *r_is_in_range = false;
5339 }
5340
5341 if (len == 0) {
5342 return 0;
5343 }
5344
5345 int framenr;
5346 cfra = cfra - iuser->sfra + 1;
5347
5348 /* cyclic */
5349 if (iuser->cycl) {
5350 cfra = ((cfra) % len);
5351 if (cfra < 0) {
5352 cfra += len;
5353 }
5354 if (cfra == 0) {
5355 cfra = len;
5356 }
5357
5358 if (r_is_in_range) {
5359 *r_is_in_range = true;
5360 }
5361 }
5362
5363 if (cfra < 0) {
5364 cfra = 0;
5365 }
5366 else if (cfra > len) {
5367 cfra = len;
5368 }
5369 else {
5370 if (r_is_in_range) {
5371 *r_is_in_range = true;
5372 }
5373 }
5374
5375 /* transform to images space */
5376 framenr = cfra;
5377 framenr = std::min(framenr, iuser->frames);
5378
5379 if (iuser->cycl) {
5380 framenr = ((framenr) % len);
5381 while (framenr < 0) {
5382 framenr += len;
5383 }
5384 if (framenr == 0) {
5385 framenr = len;
5386 }
5387 }
5388
5389 /* important to apply after else we can't loop on frames 100 - 110 for eg. */
5390 framenr += iuser->offset;
5391
5392 return framenr;
5393}
5394
5395void BKE_image_user_frame_calc(Image *ima, ImageUser *iuser, int cfra)
5396{
5397 if (iuser) {
5398 if (ima && BKE_image_is_animated(ima)) {
5399 /* Compute current frame for animated image. */
5400 bool is_in_range;
5401 const int framenr = BKE_image_user_frame_get(iuser, cfra, &is_in_range);
5402
5403 if (is_in_range) {
5404 iuser->flag |= IMA_USER_FRAME_IN_RANGE;
5405 }
5406 else {
5408 }
5409
5410 iuser->framenr = framenr;
5411 }
5412 else {
5413 /* Set fixed frame number for still image. */
5414 iuser->framenr = 0;
5415 iuser->flag |= IMA_USER_FRAME_IN_RANGE;
5416 }
5417
5418 iuser->flag &= ~IMA_NEED_FRAME_RECALC;
5419 }
5420}
5421
5422/* goes over all ImageUsers, and sets frame numbers if auto-refresh is set */
5424 ID * /*iuser_id*/,
5425 ImageUser *iuser,
5426 void *customdata)
5427{
5428 if (ima && BKE_image_is_animated(ima)) {
5429 if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
5430 int cfra = *static_cast<int *>(customdata);
5431
5432 BKE_image_user_frame_calc(ima, iuser, cfra);
5433 }
5434 }
5435}
5436
5437void BKE_image_editors_update_frame(const Main *bmain, int cfra)
5438{
5439 /* This only updates images used by the user interface. For others the
5440 * dependency graph will call BKE_image_user_id_eval_animation. */
5441 wmWindowManager *wm = bmain->wm.first();
5443}
5444
5446 ID * /*iuser_id*/,
5447 ImageUser * /*iuser*/,
5448 void *customdata)
5449{
5450 if (ima && BKE_image_is_animated(ima)) {
5451 *static_cast<bool *>(customdata) = true;
5452 }
5453}
5454
5456{
5457 /* For the dependency graph, this does not consider nested node
5458 * trees as these are handled as their own data-block. */
5459 bool has_animation = false;
5460 bool skip_nested_nodes = true;
5461 image_walk_id_all_users(id, skip_nested_nodes, &has_animation, image_user_id_has_animation);
5462 return has_animation;
5463}
5464
5466 ID * /*iduser_id*/,
5467 ImageUser *iuser,
5468 void *customdata)
5469{
5470 if (ima && BKE_image_is_animated(ima)) {
5471 Depsgraph *depsgraph = static_cast<Depsgraph *>(customdata);
5472
5473 if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC) ||
5474 (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER))
5475 {
5476 float cfra = DEG_get_ctime(depsgraph);
5477
5478 BKE_image_user_frame_calc(ima, iuser, cfra);
5479 }
5480 }
5481}
5482
5483void BKE_image_user_id_eval_animation(Depsgraph *depsgraph, ID *id)
5484{
5485 /* This is called from the dependency graph to update the image
5486 * users in data-blocks. It computes the current frame number
5487 * and tags the image to be refreshed.
5488 * This does not consider nested node trees as these are handled
5489 * as their own data-block. */
5490 bool skip_nested_nodes = true;
5491 image_walk_id_all_users(id, skip_nested_nodes, depsgraph, image_user_id_eval_animation);
5492}
5493
5494void BKE_image_user_file_path(const ImageUser *iuser, const Image *ima, char *filepath)
5495{
5496 BKE_image_user_file_path_ex(G_MAIN, iuser, ima, filepath, true, true);
5497}
5498
5500 const ImageUser *iuser,
5501 const Image *ima,
5502 char *filepath,
5503 const bool resolve_udim,
5504 const bool resolve_multiview)
5505{
5506 if (resolve_multiview && BKE_image_is_multiview(ima) && iuser) {
5507 ImageView *iv = static_cast<ImageView *>(BLI_findlink(&ima->views, iuser->view));
5508 if (iv && iv->filepath[0]) {
5509 BLI_strncpy(filepath, iv->filepath, FILE_MAX);
5510 }
5511 else {
5512 BLI_strncpy(filepath, ima->filepath, FILE_MAX);
5513 }
5514 }
5515 else {
5516 BLI_strncpy(filepath, ima->filepath, FILE_MAX);
5517 }
5518
5519 if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_TILED)) {
5520 char head[FILE_MAX], tail[FILE_MAX];
5521 ushort numlen;
5522
5523 int index;
5524 if (ima->source == IMA_SRC_SEQUENCE) {
5525 index = iuser ? iuser->framenr : ima->lastframe;
5526 BLI_path_sequence_decode(filepath, head, sizeof(head), tail, sizeof(tail), &numlen);
5527 BLI_path_sequence_encode(filepath, FILE_MAX, head, tail, numlen, index);
5528 }
5529 else if (resolve_udim) {
5531
5532 eUDIM_TILE_FORMAT tile_format;
5533 char *udim_pattern = BKE_image_get_tile_strformat(filepath, &tile_format);
5534 BKE_image_set_filepath_from_tile_number(filepath, udim_pattern, tile_format, index);
5535 MEM_SAFE_DELETE(udim_pattern);
5536 }
5537 }
5538
5539 BLI_path_abs(filepath, ID_BLEND_PATH(bmain, &ima->id));
5540}
5541
5543{
5544 void *lock;
5545 ImBuf *ibuf = BKE_image_acquire_ibuf(image, nullptr, &lock);
5546 bool result = ibuf ? ibuf->can_contain_alpha() : false;
5548 return result;
5549}
5550
5551void BKE_image_get_size(Image *image, ImageUser *iuser, int *r_width, int *r_height)
5552{
5553 ImBuf *ibuf = nullptr;
5554 void *lock;
5555
5556 if (image != nullptr) {
5557 ibuf = BKE_image_acquire_ibuf(image, iuser, &lock);
5558 }
5559
5560 if (ibuf && ibuf->x > 0 && ibuf->y > 0) {
5561 *r_width = ibuf->x;
5562 *r_height = ibuf->y;
5563 }
5564 else if (image != nullptr && image->type == IMA_TYPE_R_RESULT && iuser != nullptr &&
5565 iuser->scene != nullptr)
5566 {
5567 BKE_render_resolution(&iuser->scene->r, true, r_width, r_height);
5568 }
5569 else {
5570 *r_width = IMG_SIZE_FALLBACK;
5571 *r_height = IMG_SIZE_FALLBACK;
5572 }
5573
5574 if (image != nullptr) {
5576 }
5577}
5578
5579void BKE_image_get_size_fl(Image *image, ImageUser *iuser, float r_size[2])
5580{
5581 int width, height;
5582 BKE_image_get_size(image, iuser, &width, &height);
5583
5584 r_size[0] = float(width);
5585 r_size[1] = float(height);
5586}
5587
5588void BKE_image_get_aspect(Image *image, float *r_aspx, float *r_aspy)
5589{
5590 *r_aspx = 1.0;
5591
5592 /* x is always 1 */
5593 if (image) {
5594 *r_aspy = image->aspy / image->aspx;
5595 }
5596 else {
5597 *r_aspy = 1.0f;
5598 }
5599}
5600
5602{
5603 ImageUser iuser;
5604 BKE_imageuser_default(&iuser);
5605 void *lock;
5606 ImBuf *ibuf;
5607 uchar *pixels = nullptr;
5608
5609 iuser.framenr = frame;
5610 iuser.tile = tile;
5611
5612 ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock);
5613
5614 if (ibuf) {
5615 pixels = ibuf->byte_data_for_write();
5616
5617 if (pixels) {
5618 pixels = MEM_dupalloc(pixels);
5619 }
5620
5622 }
5623
5624 if (!pixels) {
5625 return nullptr;
5626 }
5627
5628 return pixels;
5629}
5630
5632{
5633 ImageUser iuser;
5634 BKE_imageuser_default(&iuser);
5635 void *lock;
5636 ImBuf *ibuf;
5637 float *pixels = nullptr;
5638
5639 iuser.framenr = frame;
5640 iuser.tile = tile;
5641
5642 ibuf = BKE_image_acquire_ibuf(image, &iuser, &lock);
5643
5644 if (ibuf) {
5645 pixels = ibuf->float_data_for_write();
5646
5647 if (pixels) {
5648 pixels = MEM_dupalloc(pixels);
5649 }
5650
5652 }
5653
5654 if (!pixels) {
5655 return nullptr;
5656 }
5657
5658 return pixels;
5659}
5660
5662{
5663 return BLI_path_sequence_decode(image->filepath, nullptr, 0, nullptr, 0, nullptr);
5664}
5665
5667{
5668 return (ima->anims.is_empty() == false);
5669}
5670
5672{
5673 return (ima->packedfiles.is_empty() == false);
5674}
5675
5677{
5678 /* This could be improved to detect cases like //../../, currently path
5679 * remapping empty file paths empty. */
5680 return ima->filepath[0] != '\0';
5681}
5682
5684{
5686}
5687
5689{
5690 return ELEM(image->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE);
5691}
5692
5697
5698bool BKE_image_is_dirty_writable(Image *image, bool *r_is_writable)
5699{
5700 bool is_dirty = false;
5701 bool is_writable = false;
5702
5703 std::scoped_lock lock(image->runtime->cache_mutex);
5704 if (image->runtime->cache != nullptr) {
5705 ImBufCacheIter *iter = IMB_cacheIter_new(image->runtime->cache);
5706
5707 while (!IMB_cacheIter_done(iter)) {
5708 ImBuf *ibuf = IMB_cacheIter_getImBuf(iter);
5709 if (ibuf != nullptr && ibuf->userflags & IB_BITMAPDIRTY) {
5710 is_writable = BKE_image_buffer_format_writable(ibuf);
5711 is_dirty = true;
5712 break;
5713 }
5714 IMB_cacheIter_step(iter);
5715 }
5716 IMB_cacheIter_free(iter);
5717 }
5718
5719 if (r_is_writable) {
5720 *r_is_writable = is_writable;
5721 }
5722
5723 return is_dirty;
5724}
5725
5727{
5728 return BKE_image_is_dirty_writable(image, nullptr);
5729}
5730
5732{
5733 ImageFormatData im_format;
5734 ImbFormatOptions options_dummy;
5735 BKE_image_format_from_imbuf(&im_format, ibuf);
5736 return (BKE_imtype_to_ftype(im_format.imtype, &options_dummy) == ibuf->ftype);
5737}
5738
5740{
5741 std::scoped_lock lock(image->runtime->cache_mutex);
5742 if (image->runtime->cache != nullptr) {
5743 ImBufCacheIter *iter = IMB_cacheIter_new(image->runtime->cache);
5744
5745 while (!IMB_cacheIter_done(iter)) {
5746 ImBuf *ibuf = IMB_cacheIter_getImBuf(iter);
5747 if (ibuf != nullptr) {
5748 ibuf->ftype = ftype;
5749 ibuf->foptions = *options;
5750 }
5751 IMB_cacheIter_step(iter);
5752 }
5753 IMB_cacheIter_free(iter);
5754 }
5755}
5756
5758{
5759 bool has_loaded_ibuf = false;
5760
5761 std::scoped_lock lock(image->runtime->cache_mutex);
5762 if (image->runtime->cache != nullptr) {
5763 ImBufCacheIter *iter = IMB_cacheIter_new(image->runtime->cache);
5764
5765 while (!IMB_cacheIter_done(iter)) {
5766 ImBuf *ibuf = IMB_cacheIter_getImBuf(iter);
5767 const ImageCacheKey *key = static_cast<const ImageCacheKey *>(
5769 if (ibuf != nullptr && !image_index_is_gpu_only(key->index)) {
5770 has_loaded_ibuf = true;
5771 break;
5772 }
5773 IMB_cacheIter_step(iter);
5774 }
5775 IMB_cacheIter_free(iter);
5776 }
5777
5778 return has_loaded_ibuf;
5779}
5780
5782{
5783 BLI_assert(!BLI_path_is_rel(filepath));
5784 ImBuf *ibuf = nullptr;
5785
5786 std::scoped_lock lock(image->runtime->cache_mutex);
5787 if (image->runtime->cache != nullptr) {
5788 ImBufCacheIter *iter = IMB_cacheIter_new(image->runtime->cache);
5789
5790 while (!IMB_cacheIter_done(iter)) {
5791 ImBuf *current_ibuf = IMB_cacheIter_getImBuf(iter);
5792 if (current_ibuf != nullptr && current_ibuf->filepath == filepath) {
5793 ibuf = current_ibuf;
5794 IMB_refImBuf(ibuf);
5795 break;
5796 }
5797 IMB_cacheIter_step(iter);
5798 }
5799 IMB_cacheIter_free(iter);
5800 }
5801
5802 return ibuf;
5803}
5804
5806{
5807 ImBuf *ibuf = nullptr;
5808
5809 std::scoped_lock lock(image->runtime->cache_mutex);
5810 if (image->runtime->cache != nullptr) {
5811 ImBufCacheIter *iter = IMB_cacheIter_new(image->runtime->cache);
5812
5813 while (!IMB_cacheIter_done(iter)) {
5814 ibuf = IMB_cacheIter_getImBuf(iter);
5815 const ImageCacheKey *key = static_cast<const ImageCacheKey *>(
5817 if (ibuf != nullptr && !image_index_is_gpu_only(key->index)) {
5818 IMB_refImBuf(ibuf);
5819 break;
5820 }
5821 IMB_cacheIter_step(iter);
5822 }
5823 IMB_cacheIter_free(iter);
5824 }
5825
5826 return ibuf;
5827}
5828
5830{
5831 ImageView *iv;
5832 Scene *scene = iuser->scene;
5833 const bool is_multiview = ((scene->r.scemode & R_MULTIVIEW) != 0) &&
5834 ((ima->flag & IMA_USE_VIEWS) != 0);
5835
5836 /* reset the image views */
5838
5839 if (!is_multiview) {
5840 /* nothing to do */
5841 }
5842 else if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
5843 const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
5844
5845 for (int i = 0; i < 2; i++) {
5846 image_add_view(ima, names[i], ima->filepath);
5847 }
5848 return;
5849 }
5850 else {
5851 /* R_IMF_VIEWS_INDIVIDUAL */
5852 char prefix[FILE_MAX] = {'\0'};
5853 char *filepath = ima->filepath;
5854 const char *ext = nullptr;
5855
5856 BKE_scene_multiview_view_prefix_get(scene, filepath, prefix, &ext);
5857
5858 if (prefix[0] == '\0') {
5860 return;
5861 }
5862
5863 /* create all the image views */
5864 for (SceneRenderView &srv : scene->r.views) {
5865 if (BKE_scene_multiview_is_render_view_active(&scene->r, &srv)) {
5866 char filepath_view[FILE_MAX];
5867 SNPRINTF(filepath_view, "%s%s%s", prefix, srv.suffix, ext);
5868 image_add_view(ima, srv.name, filepath_view);
5869 }
5870 }
5871
5872 /* check if the files are all available */
5873 iv = ima->views.last();
5874 while (iv) {
5875 int file;
5876 char filepath[FILE_MAX];
5877
5878 STRNCPY(filepath, iv->filepath);
5879 BLI_path_abs(filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
5880
5881 /* exists? */
5882 file = BLI_open(filepath, O_BINARY | O_RDONLY, 0);
5883 if (file == -1) {
5884 ImageView *iv_del = iv;
5885 iv = iv->prev;
5886 BLI_remlink(&ima->views, iv_del);
5887 MEM_delete(iv_del);
5888 }
5889 else {
5890 iv = iv->prev;
5891 close(file);
5892 }
5893 }
5894
5895 /* all good */
5896 if (!BKE_image_is_multiview(ima)) {
5898 }
5899 }
5900}
5901
5903
5904/* -------------------------------------------------------------------- */
5907
5909{
5910 RenderSlot *slot = MEM_new<RenderSlot>("Image new Render Slot");
5911 if (name && name[0]) {
5912 STRNCPY_UTF8(slot->name, name);
5913 }
5914 else {
5915 int n = ima->renderslots.count() + 1;
5916 SNPRINTF_UTF8(slot->name, DATA_("Slot %d"), n);
5917 }
5918 BLI_addtail(&ima->renderslots, slot);
5919 return slot;
5920}
5921
5922bool BKE_image_remove_renderslot(Image *ima, ImageUser *iuser, int slot)
5923{
5924 if (slot == ima->last_render_slot) {
5925 /* Don't remove render slot while rendering to it. */
5926 if (G.is_rendering) {
5927 return false;
5928 }
5929 }
5930
5931 int num_slots = ima->renderslots.count();
5932 if (slot >= num_slots || num_slots == 1) {
5933 return false;
5934 }
5935
5936 RenderSlot *remove_slot = static_cast<RenderSlot *>(BLI_findlink(&ima->renderslots, slot));
5937 RenderSlot *current_slot = static_cast<RenderSlot *>(
5938 BLI_findlink(&ima->renderslots, ima->render_slot));
5939 RenderSlot *current_last_slot = static_cast<RenderSlot *>(
5940 BLI_findlink(&ima->renderslots, ima->last_render_slot));
5941
5942 RenderSlot *next_slot;
5943 if (current_slot == remove_slot) {
5944 next_slot = static_cast<RenderSlot *>(
5945 BLI_findlink(&ima->renderslots, (slot == num_slots - 1) ? slot - 1 : slot + 1));
5946 }
5947 else {
5948 next_slot = current_slot;
5949 }
5950
5951 /* If the slot to be removed is the slot with the last render,
5952 * make another slot the last render slot. */
5953 if (remove_slot == current_last_slot) {
5954 /* Choose the currently selected slot unless that one is being removed,
5955 * in that case take the next one. */
5956 RenderSlot *next_last_slot;
5957 if (current_slot == remove_slot) {
5958 next_last_slot = next_slot;
5959 }
5960 else {
5961 next_last_slot = current_slot;
5962 }
5963
5964 if (iuser == nullptr || iuser->scene == nullptr) {
5965 return false;
5966 }
5967 Render *re = RE_GetSceneRender(iuser->scene);
5968 if (re != nullptr) {
5969 RE_SwapResult(re, &current_last_slot->render);
5970 RE_SwapResult(re, &next_last_slot->render);
5971 }
5972 current_last_slot = next_last_slot;
5973 }
5974
5975 current_slot = next_slot;
5976
5977 BLI_remlink(&ima->renderslots, remove_slot);
5978
5979 ima->render_slot = BLI_findindex(&ima->renderslots, current_slot);
5980 ima->last_render_slot = BLI_findindex(&ima->renderslots, current_last_slot);
5981
5982 if (remove_slot->render) {
5983 RE_FreeRenderResult(remove_slot->render);
5984 }
5985 MEM_delete(remove_slot);
5986
5987 return true;
5988}
5989
5990bool BKE_image_clear_renderslot(Image *ima, ImageUser *iuser, int slot)
5991{
5992 if (slot == ima->last_render_slot) {
5993 if (!iuser) {
5994 return false;
5995 }
5996 if (G.is_rendering) {
5997 return false;
5998 }
5999 Render *re = RE_GetSceneRender(iuser->scene);
6000 if (!re) {
6001 return false;
6002 }
6003 RE_ClearResult(re);
6004 return true;
6005 }
6006
6007 RenderSlot *render_slot = static_cast<RenderSlot *>(BLI_findlink(&ima->renderslots, slot));
6008 if (!render_slot) {
6009 return false;
6010 }
6011 if (render_slot->render) {
6012 RE_FreeRenderResult(render_slot->render);
6013 render_slot->render = nullptr;
6014 }
6015 return true;
6016}
6017
6019{
6020 /* Can be null for images without render slots. */
6021 return static_cast<RenderSlot *>(BLI_findlink(&ima->renderslots, index));
6022}
6023
6025
6026/* -------------------------------------------------------------------- */
6029
6030/* Recognize a filename written by Cycles `unique_filename_tx`, which has the form
6031 * `<source_basename>.<digits>-<32 hex chars>.tx` */
6032static bool is_texture_cache_filename(StringRef relname, StringRef source_basename)
6033{
6034 if (!relname.endswith(".tx")) {
6035 return false;
6036 }
6037 relname = relname.drop_known_suffix(".tx");
6038 if (!relname.startswith(source_basename)) {
6039 return false;
6040 }
6041 relname = relname.drop_known_prefix(source_basename);
6042 if (!relname.startswith(".")) {
6043 return false;
6044 }
6045 relname = relname.drop_known_prefix(".");
6046
6047 int64_t dash_pos = 0;
6048 while (dash_pos < relname.size() && relname[dash_pos] >= '0' && relname[dash_pos] <= '9') {
6049 dash_pos++;
6050 }
6051 if (dash_pos == 0 || dash_pos >= relname.size() || relname[dash_pos] != '-') {
6052 return false;
6053 }
6054 relname = relname.drop_prefix(dash_pos + 1);
6055
6056 const int64_t hex_len = 32;
6057 if (relname.size() != hex_len) {
6058 return false;
6059 }
6060 for (const char c : relname) {
6061 if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'))) {
6062 return false;
6063 }
6064 }
6065 return true;
6066}
6067
6068static void scan_texture_cache_dir(const char *dir,
6069 const char *source_filepath_abs,
6070 StringRef source_basename,
6071 FunctionRef<void(StringRef cache_filepath)> callback)
6072{
6073 if (!BLI_is_dir(dir)) {
6074 return;
6075 }
6076
6077 direntry *filelist = nullptr;
6078 const uint nentries = BLI_filelist_dir_contents(dir, &filelist);
6079 for (uint i = 0; i < nentries; i++) {
6080 if (!(filelist[i].type & S_IFREG)) {
6081 continue;
6082 }
6083 if (!is_texture_cache_filename(StringRef(filelist[i].relname), source_basename)) {
6084 continue;
6085 }
6086 /* Defensive check to not emit the original source file path. */
6087 if (STREQ(filelist[i].path, source_filepath_abs)) {
6088 continue;
6089 }
6090 callback(StringRef(filelist[i].path));
6091 }
6092 BLI_filelist_free(filelist, nentries);
6093}
6094
6096 const char *source_filepath_abs,
6097 const char *texture_cache_dir,
6098 FunctionRef<void(StringRef cache_filepath)> callback)
6099{
6100 char source_dir[FILE_MAX];
6101 char source_basename[FILE_MAXFILE];
6102 BLI_path_split_dir_part(source_filepath_abs, source_dir, sizeof(source_dir));
6103 BLI_path_split_file_part(source_filepath_abs, source_basename, sizeof(source_basename));
6104 if (source_basename[0] == '\0') {
6105 return;
6106 }
6107
6108 /* First look in user configured cache directory. */
6109 char user_dir[FILE_MAX] = "";
6110 if (texture_cache_dir && texture_cache_dir[0] != '\0') {
6111 if (BLI_path_is_abs_from_cwd(texture_cache_dir)) {
6112 STRNCPY(user_dir, texture_cache_dir);
6113 }
6114 else {
6115 BLI_path_join(user_dir, sizeof(user_dir), source_dir, texture_cache_dir);
6116 }
6117 BLI_path_normalize(user_dir);
6118 }
6119
6120 /* Also look in default cache directory. */
6121 char default_dir[FILE_MAX];
6122 BLI_path_join(default_dir, sizeof(default_dir), source_dir, "blender_tx");
6123 BLI_path_normalize(default_dir);
6124
6125 scan_texture_cache_dir(default_dir, source_filepath_abs, source_basename, callback);
6126 if (user_dir[0] != '\0' && !STREQ(user_dir, default_dir)) {
6127 scan_texture_cache_dir(user_dir, source_filepath_abs, source_basename, callback);
6128 }
6129}
6130
6132
6133} // namespace blender
#define G_MAIN
#define IMA_UDIM_MAX
Definition BKE_image.hh:56
#define IMA_SIGNAL_COLORMANAGE
Definition BKE_image.hh:184
#define IMA_SIGNAL_FREE
Definition BKE_image.hh:179
#define IMA_SIGNAL_SRC_CHANGE
Definition BKE_image.hh:181
#define IMA_SIGNAL_USER_NEW_IMAGE
Definition BKE_image.hh:183
#define IMA_SIGNAL_RELOAD
Definition BKE_image.hh:178
#define SH_NODE_TEX_IMAGE
#define CMP_NODE_CRYPTOMATTE
#define SH_NODE_TEX_ENVIRONMENT
#define TEX_NODE_IMAGE
#define CMP_NODE_IMAGE
File and directory operations.
#define O_BINARY
#define FILE_MAXFILE
#define FILE_MAX
#define BLI_path_join(...)
#define FILE_MAXDIR
#define BLI_path_cmp
#define SNPRINTF(dst, format,...)
#define SNPRINTF_UTF8(dst, format,...)
#define STRNCPY_UTF8(dst, src)
Platform independent time functions.
const char * dirname(char *path)
#define BLO_read_struct_list(reader, struct_name, list)
#define BLO_read_struct(reader, struct_name, ptr_p)
#define BLT_I18NCONTEXT_ID_IMAGE
#define DATA_(msgid)
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_STR_ERROR(clg_ref, str)
Definition CLG_log.h:196
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
#define ID_IS_LINKED(_id)
Definition DNA_ID.h:697
#define ID_BLEND_PATH_FROM_GLOBAL(_id)
Definition DNA_ID.h:691
#define ID_BLEND_PATH(_bmain, _id)
Definition DNA_ID.h:688
#define ID_IS_OVERRIDE_LIBRARY(_id)
Definition DNA_ID.h:736
#define FILTER_ID_IM
Definition DNA_ID.h:1206
Object is a sort of wrapper for general info.
#define R_STAMP_ALL
#define STEREO_LEFT_NAME
#define STEREO_LEFT_SUFFIX
#define STEREO_RIGHT_NAME
#define STEREO_RIGHT_SUFFIX
#define FRA2TIME(a)
#define IMG_SIZE_FALLBACK
Read Blender memory allocation and freeing.
int pad[32 - sizeof(int)]
volatile int lock
#define IMA_INDEX_UDIM_ATLAS
#define IMA_MAKE_INDEX(entry, index)
#define IMA_INDEX_MISSING_LAYER
#define IMA_INDEX_ENTRY(index)
#define IMA_INDEX_UDIM_TILE_MAPPING
#define POINTER_FROM_INT(i)
#define UNUSED_VARS_NDEBUG(...)
#define BLI_INLINE
#define POINTER_AS_INT(i)
#define INIT_DEFAULT_STRUCT_AFTER(struct_dst, member)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
#define STREQ(a, b)
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
const T * data() const
Definition BLI_array.hh:323
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
bool is_empty() const
Definition BLI_set.hh:614
constexpr StringRef drop_prefix(int64_t n) const
constexpr StringRef drop_known_prefix(StringRef prefix) const
constexpr StringRef drop_known_suffix(StringRef suffix) const
void append(const T &value)
bool is_empty() const
constexpr bool startswith(StringRef prefix) const
constexpr int64_t size() const
void copy_utf8_truncated(char *dst, int64_t dst_size) const
Definition string_ref.cc:28
constexpr bool endswith(StringRef suffix) const
CCL_NAMESPACE_BEGIN struct Options options
#define offsetof(t, d)
#define pf(_x, _i)
Prefetch 64.
Definition gim_memory.h:48
#define FLT_MAX
#define layer
void camera(KernelGlobals &kg, const ShadingData &sd, float3 &outview, float &outdepth, float &outdist)
float3x3 scale(float3x3 mat, float2 scale)
ccl_gpu_kernel_postfix ccl_global KernelWorkTile * tiles
const int tile_index
const ccl_global KernelWorkTile * tile
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
std::string filename(const std::string_view &str, size_t pos)
BLI_INLINE Texture * wrap(MTLTexture *texture)
const Strip * strip_topmost_get(const Scene *scene, int frame)
BMesh Iterators.
bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv)
Definition scene.cc:3241
bool BKE_image_is_multiview(const Image *ima)
char * BKE_image_get_tile_strformat(const char *filepath, eUDIM_TILE_FORMAT *r_tile_format)
int BKE_image_get_tile_from_pos(Image *ima, const float uv[2], float r_uv[2], float r_ofs[2])
static ImBuf * image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
void BKE_image_user_frame_calc(Image *ima, ImageUser *iuser, int cfra)
void BKE_image_buf_fill_color(unsigned char *rect, float *rect_float, int width, int height, const float color[4])
Definition image_gen.cc:28
static void image_init_color_management(Image *ima)
static int tile_sort_cb(const void *a, const void *b)
void * MEM_new_uninitialized(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
void IMB_colormanagement_assign_float_colorspace(ImBuf *ibuf, const char *name)
UserDef U
Definition blender.cc:58
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
RenderResult * BKE_image_acquire_renderresult(Scene *scene, Image *ima)
static bool imagecache_check_dirty(ImBuf *ibuf, void *, void *)
void BKE_icon_id_delete(ID *id)
Definition icons.cc:524
static uint imagecache_hashhash(const void *key_v)
void IMB_cacheIter_step(ImBufCacheIter *iter)
Definition cache.cc:597
void * IMB_cacheIter_getUserKey(ImBufCacheIter *iter)
Definition cache.cc:609
void BKE_packedfile_blend_write(BlendWriter *writer, const PackedFile *pf)
void BLI_hostname_get(char *buffer, size_t buffer_maxncpy)
Definition system.cc:192
bool BKE_image_is_animated(Image *image)
static ImBuf * image_load_image_file(Image *ima, ImageUser *iuser, int entry, int cfra, bool is_sequence)
__int64 int64_t
Definition BKE_text.h:90
ImBuf * IMB_makeSingleUser(ImBuf *ibuf)
size_t BLI_snprintf(char *__restrict dst, size_t dst_maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
@ IMA_AUTOSAVE_TEMPPACK
static bool image_index_is_gpu_only(const int index)
void BKE_previewimg_id_free(ID *id)
char * STRNCPY(char(&dst)[N], const char *src)
bool BKE_stamp_is_known_field(const char *field_name)
void BKE_image_multiview_index(const Image *ima, ImageUser *iuser)
bool BKE_image_scale(Image *image, int width, int height, ImageUser *iuser)
static void image_free_cached_frames(Image *image)
void BKE_ntree_update(Main &bmain, std::optional< Span< bNodeTree * > > modified_trees=std::nullopt, const NodeTreeUpdateExtraParams &params={})
@ IMA_TYPE_MULTILAYER
void BKE_image_texture_cache_filepaths_foreach(const char *source_filepath_abs, const char *cache_dir, blender::FunctionRef< void(blender::StringRef cache_filepath)> callback)
@ IMA_ALPHA_CHANNEL_PACKED
void BLF_position(int fontid, float x, float y, float z)
Definition blf.cc:390
static void image_remove_all_tiles(Image *ima)
void * BKE_libblock_alloc_in_lib(Main *bmain, std::optional< Library * > owner_library, short type, const char *name, int flag) ATTR_WARN_UNUSED_RESULT
Definition lib_id.cc:1439
bool BKE_image_clear_renderslot(Image *ima, ImageUser *iuser, int slot)
PackedFile * BKE_packedfile_duplicate(const PackedFile *pf_src)
void StampCallback(void *data, const char *propname, char *propvalue, int propvalue_maxncpy)
Definition BKE_image.hh:99
unsigned int uint
Definition BKE_text.h:55
void BKE_previewimg_blend_read(BlendDataReader *reader, PreviewImage *prv)
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
bool RE_HasCombinedLayer(const RenderResult *result)
int BLF_width_max(int fontid) ATTR_WARN_UNUSED_RESULT
Definition blf.cc:894
bool BLI_path_abs(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1
int64_t BLI_time_now_seconds_i()
Definition time.cc:36
int blf_mono_font_render
Definition blf.cc:51
static void image_buf_fill_isolated(void *usersata_v)
void BKE_ntree_update_tag_id_changed(Main *bmain, ID *id)
void BLI_addhead(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:98
int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname)
Definition scene.cc:3335
static void image_update_views_format(Image *ima, ImageUser *iuser)
static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
unsigned int BLI_filelist_dir_contents(const char *dirname, struct direntry **r_filelist)
static void imagecache_remove(Image *image, ImageCacheKey key)
ImBuf * BKE_image_get_first_ibuf(Image *image)
void id_us_plus(ID *id)
Definition lib_id.cc:433
void BKE_image_release_renderresult(Scene *scene, Image *ima, RenderResult *render_result)
void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal)
int BKE_icon_id_ensure(ID *id)
Definition icons.cc:279
static int image_get_multiview_index(Image *ima, ImageUser *iuser)
void BKE_image_packfiles_from_mem(ReportList *reports, Image *ima, char *data, size_t data_len)
void void void void void void BLI_duplicatelist(ListBase *dst, const ListBase *src) ATTR_NONNULL(1
Definition listbase.cc:834
void BKE_image_get_size(Image *image, ImageUser *iuser, int *r_width, int *r_height)
size_t IMB_get_pixel_count(const ImBuf *ibuf)
Get the length of the data of the given image buffer in pixels.
void BLF_wordwrap(int fontid, int wrap_width, BLFWrapMode mode=BLFWrapMode::Minimal)
Definition blf.cc:957
static void imagecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
Vector< uint8_t > IMB_save_image_to_buffer(ImBuf *ibuf, ImBufFlags flags)
Definition writeimage.cc:64
bool BKE_image_has_loaded_ibuf(Image *image)
static void stampdata(const Scene *scene, Object *camera, StampData *stamp_data, int do_prefix, bool use_dynamic)
static bool imagecache_check_free_anim(ImBuf *ibuf, void *userkey, void *userdata)
void BLF_buffer(int fontid, float *fbuf, unsigned char *cbuf, int w, int h, int channel_count, const ColorSpace *colorspace)
Definition blf.cc:989
void BKE_image_format_to_imbuf(ImBuf *ibuf, const ImageFormatData *imf)
void MOV_close(MovieReader *anim)
Definition movie_read.cc:70
MINLINE void copy_v2_v2(float r[2], const float a[2])
static void image_abs_path(Main *bmain, Library *owner_library, const char *filepath, char *r_filepath_abs)
void BKE_render_result_stamp_info(Scene *scene, Object *camera, RenderResult *rr, bool allocate_only)
void BKE_previewimg_blend_write(BlendWriter *writer, const PreviewImage *prv)
static void image_editors_update_frame(Image *ima, ID *, ImageUser *iuser, void *customdata)
void IMB_cache_free(ImBufCache *cache)
Definition cache.cc:446
bool BLI_exists(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:404
void RE_SwapResult(Render *re, RenderResult **rr)
void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
bool BKE_image_has_filepath(const Image *ima)
void IMB_mark_dirty(ImBuf *ibuf)
bool bool BLI_path_suffix(char *path, size_t path_maxncpy, const char *suffix, const char *sep) ATTR_NONNULL(1
StampData * BKE_stamp_data_copy(const StampData *stamp_data)
MINLINE int integer_digits_i(int i)
void(*)(ID *id, const IDCacheKey *cache_key, void **cache_p, uint flags, void *user_data) IDTypeForeachCacheFunctionCallback
unsigned short ushort
Definition BKE_text.h:56
static void image_free_data(ID *id)
bool BKE_image_fill_tile(Image *ima, ImageTile *tile)
void BKE_image_walk_all_users(const Main *mainp, void *customdata, void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
ImageTile * BKE_image_get_tile(Image *ima, int tile_number)
void BKE_color_managed_colorspace_settings_copy(ColorManagedColorspaceSettings *colorspace_settings, const ColorManagedColorspaceSettings *settings)
eImbFileType BKE_imtype_to_ftype(char imtype, ImbFormatOptions *r_options)
static bool is_texture_cache_filename(StringRef relname, StringRef source_basename)
ImBuf * MOV_decode_frame(MovieReader *anim, int frame_index, IMB_Proxy_Size preview_size)
ImBuf * BKE_image_get_ibuf_with_name(Image *image, const char *filepath)
void * BLI_findstring(const ListBase *listbase, const char *id, int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:615
static void image_walk_ntree_all_users(bNodeTree *ntree, ID *id, void *customdata, void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
ImBuf * IMB_cacheIter_getImBuf(ImBufCacheIter *iter)
Definition cache.cc:602
static bool image_memorypack_imbuf(Image *ima, ImBuf *ibuf, int view, int tile_number, const char *filepath)
static void image_foreach_cache(ID *id, IDTypeForeachCacheFunctionCallback function_callback, void *user_data)
bool BKE_imbuf_write_stamp(const Scene *scene, const RenderResult *rr, ImBuf *ibuf, const char *filepath, const ImageFormatData *imf)
static void image_tag_frame_recalc(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata)
void BKE_packedfile_free(PackedFile *pf)
void BKE_image_user_id_eval_animation(Depsgraph *depsgraph, ID *id)
void BKE_image_stamp_buf(Scene *scene, Object *camera, const StampData *stamp_data_template, ImBuf *ibuf)
void BKE_image_all_free_anim_ibufs(Main *bmain, int except_frame)
bool BKE_image_tile_filepath_exists(const char *filepath)
void IMB_refImBuf(ImBuf *ibuf)
ImBufCache * IMB_cache_create(const char *name, int keysize, GHashHashFP hashfp, GHashCmpFP cmpfp)
Definition cache.cc:270
MINLINE void sub_v2_v2v2(float r[2], const float a[2], const float b[2])
@ LOCK_DRAW_IMAGE
const char * IMB_colormanagement_get_byte_colorspace(const ImBuf *ibuf)
void BKE_image_user_file_path(const ImageUser *iuser, const Image *ima, char *filepath)
static void copy_image_packedfiles(ListBaseT< ImagePackedFile > *lb_dst, const ListBaseT< ImagePackedFile > *lb_src)
static ImBuf * load_movie_single(Image *ima, ImageUser *iuser, int frame, const int view_id)
MINLINE void srgb_to_linearrgb_v4(float linear[4], const float srgb[4])
BLI_INLINE bool BLI_listbase_is_empty(const ListBase *lb)
PackedFile * BKE_packedfile_new(ReportList *reports, const char *filepath_rel, const char *basepath)
const char * BKE_main_blendfile_path_from_global()
Definition main.cc:1063
MINLINE int max_ii(int a, int b)
ATTR_WARN_UNUSED_RESULT const BMVert * v
void IMB_cache_put(ImBufCache *cache, void *userkey, ImBuf *ibuf)
Definition cache.cc:369
bScreen * BKE_workspace_active_screen_get(const WorkSpaceInstanceHook *hook) GETTER_ATTRS
Definition workspace.cc:684
static void image_init_after_load(Image *ima, ImageUser *iuser, ImBuf *)
static ImBuf * image_get_render_result(Image *ima, ImageUser *iuser, void **r_lock)
int BKE_scene_multiview_num_views_get(const RenderData *rd)
Definition scene.cc:3193
static void image_walk_gpu_materials(ID *id, ListBaseT< LinkData > *gpu_materials, void *customdata, void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
ExrReadHandle * IMB_exr_open_multilayer(const char *filepath)
void BKE_image_get_aspect(Image *image, float *r_aspx, float *r_aspy)
ImageTile * BKE_image_add_tile(Image *ima, int tile_number, const char *label)
int BLI_open(const char *filepath, int oflag, int pmode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
static void image_init(Image *ima, eImageSource source, eImageType type)
static void image_blend_write(BlendWriter *writer, ID *id, const void *id_address)
BLI_INLINE ImBuf * image_pool_find_item(ImagePool *pool, Image *image, int entry, int index, bool *r_found)
void BKE_image_replace_imbuf(Image *image, ImBuf *ibuf)
void IMB_rectfill_area(ImBuf *ibuf, const float scene_linear_color[4], int x1, int y1, int x2, int y2)
Definition rectop.cc:1194
void BKE_id_blend_write(BlendWriter *writer, ID *id)
Definition lib_id.cc:2890
void BLF_disable(int fontid, FontFlags flag)
Definition blf.cc:331
static ImBuf * image_get_cached_ibuf_for_index_entry(Image *ima, int index, int entry, bool *r_is_cached_empty)
size_t BLI_snprintf_rlen(char *__restrict dst, size_t dst_maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
Image * BKE_image_load_in_lib(Main *bmain, std::optional< Library * > owner_library, const char *filepath, bool check_open=true)
bool RE_RenderResult_is_stereo(const RenderResult *result)
@ LIB_ID_COPY_NO_PREVIEW
static ImBuf * image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int entry, int frame)
void BKE_render_resolution(const RenderData *r, const bool use_crop, int *r_width, int *r_height)
Definition scene.cc:3168
size_t IMB_get_size_in_memory(const ImBuf *ibuf)
ImBuf * IMB_dupImBuf(const ImBuf *ibuf1)
ImBuf * IMB_cache_get(ImBufCache *cache, void *userkey, bool *r_is_cached_empty)
Definition cache.cc:403
void BKE_image_format_from_imbuf(ImageFormatData *im_format, const ImBuf *imbuf)
int int BKE_image_find_nearest_tile(const Image *image, const float co[2]) ATTR_NONNULL(2) ATTR_WARN_UNUSED_RESULT
@ IMA_GENTYPE_GRID_COLOR
Global G
Definition blender.cc:57
const char * BKE_main_blendfile_path(const Main *bmain) ATTR_NONNULL()
Definition main.cc:1058
void RE_FreeRenderResult(RenderResult *rr)
void IMB_cache_cleanup(ImBufCache *cache, bool(cleanup_check_cb)(ImBuf *ibuf, void *userkey, void *userdata), void *userdata)
Definition cache.cc:467
ImageTile * BKE_image_get_tile_from_iuser(Image *ima, const ImageUser *iuser)
bool BKE_image_is_dirty_writable(Image *image, bool *r_is_writable)
bool IMB_save_image(ImBuf *ibuf, const char *filepath, ImBufFlags flags)
Definition writeimage.cc:40
static ImBuf * image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
void BKE_stamp_data_free(StampData *stamp_data)
ImBuf * IMB_load_image_from_filepath(const char *filepath, ImBufFlags flags, ColorManagedColorspaceSettings *colorspace_settings=nullptr)
Definition readimage.cc:201
RenderSlot * BKE_image_add_renderslot(Image *ima, const char *name)
static void metadata_get_field(void *data, const char *propname, char *propvalue, int propvalue_maxncpy)
int BKE_image_find_nearest_tile_with_offset(const Image *image, const float co[2], float r_uv_offset[2]) ATTR_NONNULL(2
void * BLI_findlink(const ListBase *listbase, int number) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:541
bool BLO_read_data_is_undo(BlendDataReader *reader)
Definition readfile.cc:6819
void BLI_mempool_destroy(BLI_mempool *pool) ATTR_NONNULL(1)
int BLI_findstringindex(const ListBase *listbase, const char *id, int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:794
int BLI_findindex(const ListBase *listbase, const void *vlink) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:593
BLI_INLINE bool image_quick_test(Image *ima, const ImageUser *iuser)
Render * RE_GetSceneRender(const Scene *scene)
@ G_FILE_AUTOPACK
void BLF_size(int fontid, float size)
Definition blf.cc:445
ImBuf * BKE_image_acquire_ibuf_gpu(Image *ima, ImageUser *iuser, void **r_lock, bool *r_load_failed=nullptr, bool cached_only=false)
void BKE_image_set_filepath_from_tile_number(char *filepath, const char *pattern, eUDIM_TILE_FORMAT tile_format, int tile_number)
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
MovieReader * MOV_open_file(const char *filepath, const ImBufFlags ib_flags, const int streamindex, const bool keep_original_colorspace, ColorManagedColorspaceSettings *colorspace_settings)
void BKE_image_editors_update_frame(const Main *bmain, int cfra)
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
bool BKE_image_remove_tile(Image *ima, ImageTile *tile)
void IMB_freeImBuf(ImBuf *ibuf)
void BKE_icon_changed(int icon_id)
Definition icons.cc:215
static uintptr_t image_mem_size(Image *image)
static void image_get_entry_and_index(Image *ima, ImageUser *iuser, int *r_entry, int *r_index)
const char * BKE_scene_find_last_marker_name(const Scene *scene, int frame)
Definition scene.cc:2514
void * MEM_new_zeroed(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
static float distance_squared_to_udim(const float co[2], const float udim[2])
static ImageTile * imagetile_alloc(int tile_number)
static void image_foreach_texture_cache_path(BPathForeachPathData *bpath_data, const char *source_filepath_abs, const char *cache_dir)
ImBufCacheIter * IMB_cacheIter_new(ImBufCache *cache)
Definition cache.cc:577
unsigned char uchar
Definition BKE_text.h:58
static int image_get_tile_number_from_iuser(const Image *ima, const ImageUser *iuser)
unsigned char * BKE_image_get_pixels_for_frame(Image *image, int frame, int tile)
Image * BKE_image_load_exists(Main *bmain, const char *filepath, bool check_open=true, bool *r_exists=nullptr)
void imagecache_put(Image *image, ImageCacheKey key, ImBuf *ibuf)
bool BKE_image_is_stereo(const Image *ima)
RenderPass * BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
void BLI_remlink(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:138
void DEG_id_tag_update(ID *id, unsigned int flags)
const char * IMB_colormanagement_role_colorspace_name_get(int role)
ImBuf * BKE_image_acquire_multilayer_view_ibuf(const RenderData &render_data, Image &image, const ImageUser &image_user, const char *pass_name, const char *view_name)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
BMesh const char void * data
void BLI_insertlinkafter(ListBase *listbase, void *vprevlink, void *vnewlink) ATTR_NONNULL(1)
Definition listbase.cc:339
void BKE_image_free_packedfiles(Image *image)
static void image_blend_read_after_liblink(BlendLibReader *reader, ID *id)
bool BLI_path_is_abs_from_cwd(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
BLI_mempool * BLI_mempool_create(unsigned int esize, unsigned int elem_num, unsigned int pchunk, unsigned int flag) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
bool BKE_image_user_match(const ImageUser &a, const ImageUser &b)
static void image_foreach_expanded_path(BPathForeachPathData *bpath_data, const char *expanded_path, const eBPathForeachFlag flag)
void BKE_image_merge(Main *bmain, Image *dest, Image *source)
BLI_INLINE void IMB_colormanagement_srgb_to_scene_linear_v3(float scene_linear[3], const float srgb[3])
static int get_multilayer_view_index(const Image &image, const ImageUser &image_user, const char *view_name)
void IMB_colormanagement_colorspace_settings_set(ColorManagedColorspaceSettings *settings, const char *name)
void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath)
void BKE_image_free_buffers_ex(Image *image, bool do_lock)
static void image_remove_ibuf(Image *ima, int index, int entry)
static ImBuf * imagecache_get(Image *image, ImageCacheKey key, bool *r_is_cached_empty)
MINLINE void copy_v2_v2_db(double r[2], const double a[2])
char char size_t BLI_strncpy_rlen(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
static bool image_remove_tile(Image *ima, ImageTile *tile)
RenderSlot * BKE_image_get_renderslot(Image *ima, int index)
void BLI_freelinkN(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:277
void IMB_ensure_host_buffer(ImBuf *ibuf)
RenderResult * RE_MultilayerConvert(ExrReadHandle *exrhandle, const char *colorspace, bool predivide, int rectx, int recty)
bool void BLI_path_rel(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1)
char BKE_image_alpha_mode_from_extension_ex(const char *filepath)
BLI_INLINE bool BLI_listbase_count_is_equal_to(const ListBase *listbase, const int count_cmp)
LinkData * BLI_genericNodeN(void *data)
Definition listbase.cc:936
MovieReader * openanim(const char *filepath, ImBufFlags ibuf_flags, int streamindex, bool keep_original_colorspace, ColorManagedColorspaceSettings *colorspace_settings)
int BLI_thread_is_main()
Definition threads.cc:184
static ImBuf * load_image_single(Image *ima, ImageUser *iuser, int cfra, const int view_id, const bool has_packed, const bool is_sequence, bool *r_cache_ibuf)
void IMB_partial_update_mark_full(ImBuf *ibuf)
int BLI_path_normalize(char *path) ATTR_NONNULL(1)
void BKE_image_free_data(Image *image)
Image * BKE_image_add_from_imbuf(Main *bmain, ImBuf *ibuf, const char *name)
void BKE_image_free_views(Image *image)
void BKE_image_free_old_buffers(Main *bmain)
static void image_user_id_has_animation(Image *ima, ID *, ImageUser *, void *customdata)
void BKE_color_managed_colorspace_settings_init(ColorManagedColorspaceSettings *colorspace_settings)
bool IMB_cacheIter_done(ImBufCacheIter *iter)
Definition cache.cc:592
void BKE_image_pool_free(ImagePool *pool)
void BKE_image_ensure_tile_token_filename_only(char *filename, size_t filename_maxncpy)
void BKE_id_free(Main *bmain, void *idv)
eEvaluationMode DEG_get_mode(const Depsgraph *graph)
int BLI_listbase_count(const ListBase *listbase) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:531
void BKE_bpath_foreach_path_readonly_process(BPathForeachPathData *bpath_data, const char *path)
Definition bpath.cc:161
int BLI_listbase_count_at_most(const ListBase *listbase, int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:518
void BKE_image_free_gpu_udim_textures(Image *ima)
Definition image_gpu.cc:812
void BLI_insertlinkbefore(ListBase *listbase, void *vnextlink, void *vnewlink) ATTR_NONNULL(1)
Definition listbase.cc:378
void BKE_image_ensure_tile_token(char *filepath, size_t filepath_maxncpy)
bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
Definition scene.cc:3224
void BKE_image_free_all_textures(Main *bmain)
void IMB_exr_close(ExrReadHandle *handle)
static bool image_views_match_render_views(const Image *image, const RenderData *render_data)
void BKE_image_buf_fill_checker(unsigned char *rect, float *rect_float, int width, int height)
Definition image_gen.cc:152
Image * BKE_image_load_exists_in_lib(Main *bmain, std::optional< Library * > owner_library, const char *filepath, bool check_open=true, bool *r_exists=nullptr)
static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int entry)
_W64 unsigned int uintptr_t
Definition BKE_text.h:120
static RenderPass * image_render_pass_get(RenderLayer *rl, const int pass, const int view, int *r_passindex)
void BKE_imbuf_stamp_info(const RenderResult *rr, ImBuf *ibuf)
void void BLI_listbase_sort(ListBase *listbase, int(*cmp)(const void *, const void *)) ATTR_NONNULL(1
Definition listbase.cc:319
ListBaseT< GPUMaterialTexture > GPU_material_textures(GPUMaterial *material)
void BKE_image_init_imageuser(Image *ima, ImageUser *iuser)
static void image_free_tile(Image *ima, ImageTile *tile)
void IMB_colormanagement_assign_byte_colorspace(ImBuf *ibuf, const char *name)
static void image_free_packedfiles(Image *ima)
bool BLI_is_dir(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:457
void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
bool BKE_image_autosave_memorypack(Image *ima)
ImBuf * IMB_allocImBuf(unsigned int x, unsigned int y, ImBufFlags flags)
bool BKE_image_get_tile_info(char *filepath, ListBaseT< LinkData > *tiles, int *r_tile_start, int *r_tile_range)
RenderResult * RE_AcquireResultRead(Render *re)
ImBuf * BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
void BLF_buffer_col(int fontid, const float srgb_color[4]) ATTR_NONNULL(2)
Definition blf.cc:1057
void BKE_image_packfile_ensure(Main *bmain, Image *image, ReportList *reports, const char *data, int data_len)
void id_us_ensure_real(ID *id)
Definition lib_id.cc:388
eBPathForeachFlag
Definition BKE_bpath.hh:39
@ BKE_BPATH_FOREACH_PATH_EXPAND_TOKENS
Definition BKE_bpath.hh:87
@ BKE_BPATH_FOREACH_PATH_EXPAND_CACHES
Definition BKE_bpath.hh:97
@ BKE_BPATH_FOREACH_PATH_SKIP_PACKED
Definition BKE_bpath.hh:49
@ BKE_BPATH_FOREACH_PATH_EXPAND_SEQUENCES
Definition BKE_bpath.hh:92
@ BKE_BPATH_FOREACH_PATH_RELOAD_EDITED
Definition BKE_bpath.hh:81
@ BKE_BPATH_FOREACH_PATH_RESOLVE_TOKEN
Definition BKE_bpath.hh:54
MINLINE float len_squared_v2(const float v[2]) ATTR_WARN_UNUSED_RESULT
void BKE_previewimg_id_copy(ID *new_id, const ID *old_id)
static ImBuf * add_ibuf_for_tile(Image *ima, ImageTile *tile)
void IMB_cache_set_getdata_callback(ImBufCache *cache, ImBufCacheGetKeyDataFP getdatafp)
Definition cache.cc:294
ImBuf * IMB_load_image_from_memory(const unsigned char *mem, size_t size, ImBufFlags flags, const char *descr, const char *filepath=nullptr, ColorManagedColorspaceSettings *colorspace_settings=nullptr)
Definition readimage.cc:132
static void image_copy_data(Main *, std::optional< Library * >, ID *id_dst, const ID *id_src, const int flag)
void BKE_bpath_sequence_filepaths_foreach(const char *abs_filepath, blender::FunctionRef< void(blender::StringRef frame_filepath)> callback)
static Set< const ImBuf * > image_multilayer_ibufs(const Image &ima)
int BLF_height_max(int fontid) ATTR_WARN_UNUSED_RESULT
Definition blf.cc:883
void BLI_filelist_free(struct direntry *filelist, unsigned int nrentries)
void void void BLI_path_split_file_part(const char *filepath, char *file, size_t file_maxncpy) ATTR_NONNULL(1
size_t BLI_timecode_string_from_time(char *str, size_t maxncpy, int brevity_level, float time_seconds, double fps, short timecode_style) ATTR_NONNULL()
Definition timecode.cc:24
static void image_free_autosave_packedfiles(Image *ima)
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
static bool nearest_udim_tile_tie_break(const float best_dist_sq, const float best_uv[2], const float dist_sq, const float uv[2])
static void image_foreach_path(ID *id, BPathForeachPathData *bpath_data)
void BLI_task_isolate(void(*func)(void *userdata), void *userdata)
float * BKE_image_get_float_pixels_for_frame(Image *image, int frame, int tile)
void BKE_stamp_info_callback(void *data, StampData *stamp_data, StampCallback callback, bool noskip)
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
@ IMA_NEED_FRAME_RECALC
@ IMA_USER_FRAME_IN_RANGE
bool BKE_bpath_foreach_path_fixed_process(BPathForeachPathData *bpath_data, char *path, size_t path_maxncpy)
Definition bpath.cc:130
void IMB_ImBufFromStereo3d(const Stereo3dFormat *s3d, ImBuf *ibuf_stereo3d, ImBuf **r_ibuf_left, ImBuf **r_ibuf_right)
char * BLI_strdup(const char *str) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1) ATTR_MALLOC
void IMB_byte_from_float(ImBuf *ibuf)
@ INDEX_ID_IM
Definition DNA_ID.h:1309
bool BLI_path_extension_check_array(const char *path, const char **ext_array) ATTR_NONNULL(1
bool BLI_path_is_rel(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
bool BLI_path_extension_check(const char *path, const char *ext) ATTR_NONNULL(1
char * BLI_string_replaceN(const char *__restrict str, const char *__restrict substr_old, const char *__restrict substr_new) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
@ BLI_MEMPOOL_NOP
static ImBufFlags imbuf_alpha_flags_for_image(Image *ima)
void IMB_metadata_foreach(const ImBuf *ibuf, IMBMetadataForeachCb callback, void *userdata)
ExrReadHandle * IMB_exr_open_multilayer_from_memory(const uchar *mem, size_t size)
std::mutex Mutex
Definition BLI_mutex.hh:51
void BKE_image_ensure_viewer_views(const RenderData *rd, Image *ima, ImageUser *iuser)
Image * BKE_image_ensure_viewer(Main *bmain, int type, const char *name)
int BLF_descender(int fontid) ATTR_WARN_UNUSED_RESULT
Definition blf.cc:905
static void image_tag_reload(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata)
static void image_walk_id_all_users(ID *id, bool skip_nested_nodes, void *customdata, void callback(Image *ima, ID *iuser_id, ImageUser *iuser, void *customdata))
int BKE_image_get_tile_label(const Image *ima, const ImageTile *tile, char *label, int label_maxncpy)
@ ID_RECALC_SYNC_TO_EVAL
Definition DNA_ID.h:1118
StampData * BKE_stamp_info_from_scene_static(const Scene *scene)
ID_Type GS(const char *name)
Definition DNA_ID.h:410
bool BKE_image_has_ibuf(Image *ima, ImageUser *iuser)
static void image_add_view(Image *ima, const char *viewname, const char *filepath)
void IMB_free_gpu_textures(ImBuf *ibuf)
Definition util_gpu.cc:835
static float distance_to_unit_interval(float x)
@ R_IMF_VIEWS_INDIVIDUAL
@ R_IMF_VIEWS_STEREO_3D
int BLI_path_sequence_decode(const char *path, char *head, size_t head_maxncpy, char *tail, size_t tail_maxncpy, unsigned short *r_digits_len)
Definition path_utils.cc:61
void BLI_path_split_dir_file(const char *filepath, char *dir, size_t dir_maxncpy, char *file, size_t file_maxncpy) ATTR_NONNULL(1
@ ID_TAG_DOIT
Definition DNA_ID.h:1029
static bool imagecache_hashcmp(const void *a_v, const void *b_v)
bool BKE_image_is_filename_tokenized(char *filepath)
static ImBuf * image_get_cached_ibuf(Image *ima, ImageUser *iuser, int *r_entry, int *r_index, bool *r_is_cached_empty)
void BLI_path_sequence_encode(char *path, size_t path_maxncpy, const char *head, const char *tail, unsigned short numlen, int pic)
bool IMB_metadata_get_field(const IDProperty *metadata, const char *key, char *value, size_t value_maxncpy)
void BKE_image_alpha_mode_from_extension(Image *image)
void BKE_image_populate_cache_from_autosave(Image *ima)
static CLG_LogRef LOG
Definition logging.cpp:12
void BLF_draw_buffer(int fontid, const char *str, size_t str_len, ResultBLF *r_info=nullptr) ATTR_NONNULL(2)
Definition blf.cc:1087
unsigned int BLI_ghashutil_strhash_p(const void *ptr)
RenderStats * RE_GetStats(Render *re)
static Image * image_alloc(Main *bmain, std::optional< Library * > owner_library, const char *name, eImageSource source, eImageType type)
bool BLO_read_lib_is_undo(BlendLibReader *reader)
Definition readfile.cc:6848
bool BKE_image_source_is_file(const Image *ima)
static bool image_memorypack_imbuf_for_autosave(Image *ima, ImBuf *ibuf, int view, int tile_number, const char *filepath)
bool BKE_image_has_multiple_ibufs(Image *image)
static void image_blend_read_data(BlendDataReader *reader, ID *id)
static void scan_texture_cache_dir(const char *dir, const char *source_filepath_abs, StringRef source_basename, FunctionRef< void(StringRef cache_filepath)> callback)
void * BLI_mempool_alloc(BLI_mempool *pool) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL ATTR_NONNULL(1)
void BKE_packedfile_blend_read(BlendDataReader *reader, PackedFile **pf_p, StringRefNull filepath)
static void image_init_data(ID *id)
MINLINE void copy_v4_v4(float r[4], const float a[4])
MINLINE void sub_v2_v2(float r[2], const float a[2])
static void metadata_set_field(void *data, const char *propname, char *propvalue, int)
void BKE_image_print_memlist(Main *bmain)
void BKE_image_clear_autosave(Image *image)
int BKE_image_sequence_guess_offset(Image *image)
void BKE_image_reassign_tile(Image *ima, ImageTile *tile, int new_tile_number)
bool BKE_image_has_packedfile(const Image *image)
static void image_colorspace_from_imbuf(Image *image, const ImBuf *ibuf)
bool IMB_colormanagement_space_name_is_data(const char *name)
static const char * stamp_metadata_fields[]
static void image_user_id_eval_animation(Image *ima, ID *, ImageUser *iuser, void *customdata)
void BKE_image_get_size_fl(Image *image, ImageUser *iuser, float r_size[2])
bool IMB_scale(ImBuf *ibuf, int2 new_size, IMBScaleFilter filter, bool threaded=true)
Definition scaling.cc:467
const char * BLI_path_slash_find(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
static ImBuf * image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock, const bool ensure_host_buffer, bool *r_load_failed=nullptr, const bool cached_only=false)
@ CMP_NODE_CRYPTOMATTE_SOURCE_IMAGE
void BKE_image_free_buffers(Image *image)
int MOV_get_duration_frames(const MovieReader *anim)
void BLI_thread_unlock(int type)
Definition threads.cc:336
static void image_create_multilayer(Image *ima, ImBuf *ibuf, ExrReadHandle *handle, int framenr)
ImBuf * BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool)
Image * BKE_image_add_generated(Main *bmain, unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short gen_type, const float color[4], bool stereo3d, bool is_data, bool tiled)
void RE_ReferenceRenderResult(RenderResult *rr)
void IMB_cache_remove(ImBufCache *cache, void *userkey)
Definition cache.cc:395
void BKE_image_file_format_set(Image *image, eImbFileType ftype, const ImbFormatOptions *options)
void BKE_imageuser_default(ImageUser *iuser)
PackedFile * BKE_packedfile_new_from_memory(const void *mem, int memlen, const ImplicitSharingInfo *sharing_info=nullptr)
int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, bool *r_is_in_range)
MINLINE int min_ii(int a, int b)
bool BLI_is_file(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:469
static void image_free_anims(Image *ima)
void BKE_scene_multiview_view_prefix_get(const Scene *scene, const char *filepath, char *r_prefix, const char **r_ext)
Definition scene.cc:3417
size_t BLI_timecode_string_from_time_simple(char *str, size_t maxncpy, double time_seconds) ATTR_NONNULL()
Definition timecode.cc:172
float DEG_get_ctime(const Depsgraph *graph)
void BKE_image_multilayer_stamp_info_callback(void *data, const Image &image, StampCallback callback, bool noskip)
void BKE_image_buf_fill_checker_color(unsigned char *rect, float *rect_float, int width, int height)
Definition image_gen.cc:372
bool BKE_image_remove_renderslot(Image *ima, ImageUser *iuser, int slot)
MINLINE void zero_v2(float r[2])
eUDIM_TILE_FORMAT
Definition BKE_image.hh:505
@ UDIM_TILE_FORMAT_UVTILE
Definition BKE_image.hh:508
@ UDIM_TILE_FORMAT_NONE
Definition BKE_image.hh:506
@ UDIM_TILE_FORMAT_UDIM
Definition BKE_image.hh:507
bool BKE_imbuf_write(ImBuf *ibuf, const char *filepath, const ImageFormatData *imf)
static void stampdata_from_template(StampData *stamp_data, const Scene *scene, const StampData *stamp_data_template, bool do_prefix)
bool BLI_path_extension_check_n(const char *path,...) ATTR_NONNULL(1) ATTR_SENTINEL(0)
bool BKE_image_get_tile_number_from_filepath(const char *filepath, const char *pattern, eUDIM_TILE_FORMAT tile_format, int *r_tile_number)
ImBuf * BKE_image_preview(Image *ima, short max_size, short *r_width, short *r_height)
const char * IMB_colormanagement_get_float_colorspace(const ImBuf *ibuf)
void IMB_cacheIter_free(ImBufCacheIter *iter)
Definition cache.cc:587
bool BLI_file_ensure_parent_dir_exists(const char *filepath) ATTR_NONNULL(1)
Definition fileops_c.cc:454
bool BKE_image_is_multilayer(const Image *ima)
void BLF_enable(int fontid, FontFlags flag)
Definition blf.cc:322
void RE_AcquireResultImage(Render *re, RenderResult *rr, const int view_id)
void IMB_metadata_set_field(IDProperty *metadata, const char *key, const char *value)
@ BLF_WORD_WRAP
Definition BLF_enums.hh:42
void BKE_image_pool_release_ibuf(Image *ima, ImBuf *ibuf, ImagePool *pool)
void BLI_thread_lock(int type)
Definition threads.cc:331
MovieReader * openanim_noload(const char *filepath, ImBufFlags flags, int streamindex, bool keep_original_colorspace, ColorManagedColorspaceSettings *colorspace_settings)
bool BKE_imbuf_write_as(ImBuf *ibuf, const char *filepath, const ImageFormatData *imf, bool save_copy)
void BKE_stamp_info_from_imbuf(RenderResult *rr, ImBuf *ibuf)
Image * BKE_image_load(Main *bmain, const char *filepath, bool check_open=true)
static void metadata_copy_custom_fields(const char *field, const char *value, void *rr_v)
bool BKE_image_buffer_format_writable(ImBuf *ibuf)
void BKE_image_get_tile_uv(const Image *ima, const int tile_number, float r_uv[2])
void BKE_image_user_file_path_ex(const Main *bmain, const ImageUser *iuser, const Image *ima, char *filepath, const bool resolve_udim, const bool resolve_multiview)
static int image_num_viewfiles(Image *ima)
void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
static void image_viewer_create_views(const RenderData *rd, Image *ima)
@ IDTYPE_FLAGS_NO_ANIMDATA
Definition BKE_idtype.hh:52
@ IDTYPE_FLAGS_APPEND_IS_REUSABLE
Definition BKE_idtype.hh:50
#define floorf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define BUFF_MARGIN_X
#define CALL(member, value_str)
#define BUFF_MARGIN_Y
#define TEXT_SIZE_CHECK(str, w, h)
#define TEXT_SIZE_CHECK_WORD_WRAP(str, w, h)
void write_id_struct(const void *id_address, const T *id, BlendStructWriterTypedFn< T > fn=nullptr)
void write_struct_list(const ListBaseT< T > *list, BlendStructWriterTypedFn< T > fn=nullptr)
void write_struct(const T *data, BlendStructWriterTypedFn< T > fn=nullptr)
bool is_undo() const
unsigned int id_session_uid
Definition BKE_idtype.hh:78
char name[258]
Definition DNA_ID.h:433
void * next
Definition DNA_ID.h:418
const ColorSpace * colorspace
std::atomic< gpu::Texture * > texture
ImbFormatOptions foptions
ImBufByteBuffer byte_buffer
const uint8_t * byte_data() const
uint8_t * byte_data_for_write()
Definition allocimbuf.cc:60
const float * float_data() const
std::string filepath
ImColorMode color_mode
eImbFileType ftype
float * float_data_for_write()
Definition allocimbuf.cc:79
bool can_contain_alpha() const
struct MovieReader * anim
struct PackedFile * packedfile
struct ImagePackedFile * next
struct ImageTile * next
eImage_GenFlag gen_flag
eImageUser_Flag flag
struct Scene * scene
struct ImageView * prev
struct ImageView * next
bke::library::LibraryRuntime * runtime
Definition DNA_ID.h:591
Library * curlib
Definition BKE_main.hh:366
ListBaseT< wmWindowManager > wm
Definition BKE_main.hh:415
ListBaseT< bNodeTree > nodetrees
Definition BKE_main.hh:409
ListBaseT< Camera > cameras
Definition BKE_main.hh:397
ListBaseT< Light > lights
Definition BKE_main.hh:396
ListBaseT< World > worlds
Definition BKE_main.hh:399
ListBaseT< Material > materials
Definition BKE_main.hh:392
ListBaseT< Object > objects
Definition BKE_main.hh:388
ListBaseT< Image > images
Definition BKE_main.hh:394
ListBaseT< Scene > scenes
Definition BKE_main.hh:386
ListBaseT< Tex > textures
Definition BKE_main.hh:393
eObject_EmptyDrawType empty_drawtype
ListBaseT< SceneRenderView > views
ListBaseT< RenderPass > passes
Definition RE_pipeline.h:99
struct RenderLayer * next
Definition RE_pipeline.h:91
struct RenderPass * next
Definition RE_pipeline.h:58
struct ImBuf * ibuf
Definition RE_pipeline.h:72
struct StampData * stamp_data
ListBaseT< RenderView > views
ListBaseT< RenderLayer > layers
struct ImBuf * ibuf
struct RenderResult * render
struct ImBuf * ibuf
Definition RE_pipeline.h:54
struct RenderView * next
Definition RE_pipeline.h:46
struct RenderData r
ListBaseT< SpaceLink > spacedata
struct ImageUser iuser
ListBaseT< StampDataCustomField > custom_fields
struct ImageUser iuser
struct Image * ima
struct bNodeTree * nodetree
eNodeTree_Type type
ListBaseT< struct ScrArea > areabase
struct WorkSpaceInstanceHook * workspace_hook
#define N_(msgid)