1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) Blender Foundation.
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup edrend
22  */
23 
24 /* global includes */
25 
26 #include <math.h>
27 #include <stdlib.h>
28 #include <string.h>
29 
30 #ifndef WIN32
31 #  include <unistd.h>
32 #else
33 #  include <io.h>
34 #endif
35 #include "MEM_guardedalloc.h"
36 
37 #include "BLI_blenlib.h"
38 #include "BLI_math.h"
39 #include "BLI_utildefines.h"
40 
41 #include "PIL_time.h"
42 
43 #include "BLO_readfile.h"
44 
45 #include "DNA_brush_types.h"
46 #include "DNA_camera_types.h"
47 #include "DNA_collection_types.h"
48 #include "DNA_light_types.h"
49 #include "DNA_material_types.h"
50 #include "DNA_node_types.h"
51 #include "DNA_object_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_screen_types.h"
54 #include "DNA_space_types.h"
55 #include "DNA_world_types.h"
56 
57 #include "BKE_appdir.h"
58 #include "BKE_brush.h"
59 #include "BKE_colortools.h"
60 #include "BKE_context.h"
61 #include "BKE_global.h"
62 #include "BKE_icons.h"
63 #include "BKE_idprop.h"
64 #include "BKE_image.h"
65 #include "BKE_layer.h"
66 #include "BKE_lib_id.h"
67 #include "BKE_light.h"
68 #include "BKE_main.h"
69 #include "BKE_material.h"
70 #include "BKE_node.h"
71 #include "BKE_scene.h"
72 #include "BKE_texture.h"
73 #include "BKE_world.h"
74 
75 #include "DEG_depsgraph.h"
76 #include "DEG_depsgraph_build.h"
77 #include "DEG_depsgraph_query.h"
78 
79 #include "IMB_imbuf.h"
80 #include "IMB_imbuf_types.h"
81 #include "IMB_thumbs.h"
82 
83 #include "BIF_glutil.h"
84 
85 #include "GPU_shader.h"
86 
87 #include "RE_engine.h"
88 #include "RE_pipeline.h"
89 #include "RE_shader_ext.h"
90 
91 #include "WM_api.h"
92 #include "WM_types.h"
93 
94 #include "ED_datafiles.h"
95 #include "ED_render.h"
96 #include "ED_screen.h"
97 
98 #ifndef NDEBUG
99 /* Used for database init assert(). */
100 #  include "BLI_threads.h"
101 #endif
102 
get_brush_icon(Brush * brush)103 ImBuf *get_brush_icon(Brush *brush)
104 {
105   static const int flags = IB_rect | IB_multilayer | IB_metadata;
106 
107   char path[FILE_MAX];
108   const char *folder;
109 
110   if (!(brush->icon_imbuf)) {
111     if (brush->flag & BRUSH_CUSTOM_ICON) {
112 
113       if (brush->icon_filepath[0]) {
114         /* First use the path directly to try and load the file. */
115 
116         BLI_strncpy(path, brush->icon_filepath, sizeof(brush->icon_filepath));
117         BLI_path_abs(path, ID_BLEND_PATH_FROM_GLOBAL(&brush->id));
118 
119         /* use default colorspaces for brushes */
120         brush->icon_imbuf = IMB_loadiffname(path, flags, NULL);
121 
122         /* otherwise lets try to find it in other directories */
123         if (!(brush->icon_imbuf)) {
124           folder = BKE_appdir_folder_id(BLENDER_DATAFILES, "brushicons");
125 
126           BLI_make_file_string(
127               BKE_main_blendfile_path_from_global(), path, folder, brush->icon_filepath);
128 
129           if (path[0]) {
130             /* use fefault color spaces */
131             brush->icon_imbuf = IMB_loadiffname(path, flags, NULL);
132           }
133         }
134 
135         if (brush->icon_imbuf) {
136           BKE_icon_changed(BKE_icon_id_ensure(&brush->id));
137         }
138       }
139     }
140   }
141 
142   if (!(brush->icon_imbuf)) {
143     brush->id.icon_id = 0;
144   }
145 
146   return brush->icon_imbuf;
147 }
148 
149 typedef struct ShaderPreview {
150   /* from wmJob */
151   void *owner;
152   short *stop, *do_update;
153 
154   Scene *scene;
155   ID *id, *id_copy;
156   ID *parent;
157   MTex *slot;
158 
159   /* datablocks with nodes need full copy during preview render, glsl uses it too */
160   Material *matcopy;
161   Tex *texcopy;
162   Light *lampcopy;
163   World *worldcopy;
164 
165   /** Copy of the active objects #Object.color */
166   float color[4];
167 
168   int sizex, sizey;
169   uint *pr_rect;
170   int pr_method;
171   bool own_id_copy;
172 
173   Main *bmain;
174   Main *pr_main;
175 } ShaderPreview;
176 
177 typedef struct IconPreviewSize {
178   struct IconPreviewSize *next, *prev;
179   int sizex, sizey;
180   uint *rect;
181 } IconPreviewSize;
182 
183 typedef struct IconPreview {
184   Main *bmain;
185   Scene *scene;
186   void *owner;
187   ID *id, *id_copy;
188   ListBase sizes;
189 } IconPreview;
190 
191 /* *************************** Preview for buttons *********************** */
192 
193 static Main *G_pr_main = NULL;
194 static Main *G_pr_main_grease_pencil = NULL;
195 
196 #ifndef WITH_HEADLESS
load_main_from_memory(const void * blend,int blend_size)197 static Main *load_main_from_memory(const void *blend, int blend_size)
198 {
199   const int fileflags = G.fileflags;
200   Main *bmain = NULL;
201   BlendFileData *bfd;
202 
203   G.fileflags |= G_FILE_NO_UI;
204   bfd = BLO_read_from_memory(blend, blend_size, BLO_READ_SKIP_NONE, NULL);
205   if (bfd) {
206     bmain = bfd->main;
207 
208     MEM_freeN(bfd);
209   }
210   G.fileflags = fileflags;
211 
212   return bmain;
213 }
214 #endif
215 
ED_preview_ensure_dbase(void)216 void ED_preview_ensure_dbase(void)
217 {
218 #ifndef WITH_HEADLESS
219   static bool base_initialized = false;
220   BLI_assert(BLI_thread_is_main());
221   if (!base_initialized) {
222     G_pr_main = load_main_from_memory(datatoc_preview_blend, datatoc_preview_blend_size);
223     G_pr_main_grease_pencil = load_main_from_memory(datatoc_preview_grease_pencil_blend,
224                                                     datatoc_preview_grease_pencil_blend_size);
225     base_initialized = true;
226   }
227 #endif
228 }
229 
check_engine_supports_preview(Scene * scene)230 static bool check_engine_supports_preview(Scene *scene)
231 {
232   RenderEngineType *type = RE_engines_find(scene->r.engine);
233   return (type->flag & RE_USE_PREVIEW) != 0;
234 }
235 
ED_preview_free_dbase(void)236 void ED_preview_free_dbase(void)
237 {
238   if (G_pr_main) {
239     BKE_main_free(G_pr_main);
240   }
241 
242   if (G_pr_main_grease_pencil) {
243     BKE_main_free(G_pr_main_grease_pencil);
244   }
245 }
246 
preview_get_scene(Main * pr_main)247 static Scene *preview_get_scene(Main *pr_main)
248 {
249   if (pr_main == NULL) {
250     return NULL;
251   }
252 
253   return pr_main->scenes.first;
254 }
255 
preview_collection_name(const char pr_type)256 static const char *preview_collection_name(const char pr_type)
257 {
258   switch (pr_type) {
259     case MA_FLAT:
260       return "Flat";
261     case MA_SPHERE:
262       return "Sphere";
263     case MA_CUBE:
264       return "Cube";
265     case MA_SHADERBALL:
266       return "Shader Ball";
267     case MA_CLOTH:
268       return "Cloth";
269     case MA_FLUID:
270       return "Fluid";
271     case MA_SPHERE_A:
272       return "World Sphere";
273     case MA_LAMP:
274       return "Lamp";
275     case MA_SKY:
276       return "Sky";
277     case MA_HAIR:
278       return "Hair";
279     case MA_ATMOS:
280       return "Atmosphere";
281     default:
282       BLI_assert(!"Unknown preview type");
283       return "";
284   }
285 }
286 
set_preview_visibility(Scene * scene,ViewLayer * view_layer,char pr_type,int pr_method)287 static void set_preview_visibility(Scene *scene,
288                                    ViewLayer *view_layer,
289                                    char pr_type,
290                                    int pr_method)
291 {
292   /* Set appropriate layer as visible. */
293   LayerCollection *lc = view_layer->layer_collections.first;
294   const char *collection_name = preview_collection_name(pr_type);
295 
296   for (lc = lc->layer_collections.first; lc; lc = lc->next) {
297     if (STREQ(lc->collection->id.name + 2, collection_name)) {
298       lc->collection->flag &= ~COLLECTION_RESTRICT_RENDER;
299     }
300     else {
301       lc->collection->flag |= COLLECTION_RESTRICT_RENDER;
302     }
303   }
304 
305   /* Hide floor for icon renders. */
306   LISTBASE_FOREACH (Base *, base, &view_layer->object_bases) {
307     if (STREQ(base->object->id.name + 2, "Floor")) {
308       if (pr_method == PR_ICON_RENDER) {
309         base->object->restrictflag |= OB_RESTRICT_RENDER;
310       }
311       else {
312         base->object->restrictflag &= ~OB_RESTRICT_RENDER;
313       }
314     }
315   }
316 
317   BKE_layer_collection_sync(scene, view_layer);
318 }
319 
preview_get_localized_world(ShaderPreview * sp,World * world)320 static World *preview_get_localized_world(ShaderPreview *sp, World *world)
321 {
322   if (world == NULL) {
323     return NULL;
324   }
325   if (sp->worldcopy != NULL) {
326     return sp->worldcopy;
327   }
328 
329   ID *id_copy = BKE_id_copy_ex(NULL,
330                                &world->id,
331                                NULL,
332                                LIB_ID_CREATE_LOCAL | LIB_ID_COPY_LOCALIZE |
333                                    LIB_ID_COPY_NO_ANIMDATA);
334   sp->worldcopy = (World *)id_copy;
335   BLI_addtail(&sp->pr_main->worlds, sp->worldcopy);
336   return sp->worldcopy;
337 }
338 
duplicate_ids(ID * id)339 static ID *duplicate_ids(ID *id)
340 {
341   if (id == NULL) {
342     /* Non-ID preview render. */
343     return NULL;
344   }
345 
346   switch (GS(id->name)) {
347     case ID_MA:
348     case ID_TE:
349     case ID_LA:
350     case ID_WO: {
351       ID *id_copy = BKE_id_copy_ex(
352           NULL, id, NULL, LIB_ID_CREATE_LOCAL | LIB_ID_COPY_LOCALIZE | LIB_ID_COPY_NO_ANIMDATA);
353       return id_copy;
354     }
355     case ID_IM:
356     case ID_BR:
357     case ID_SCR:
358       return NULL;
359     default:
360       BLI_assert(!"ID type preview not supported.");
361       return NULL;
362   }
363 }
364 
365 /* call this with a pointer to initialize preview scene */
366 /* call this with NULL to restore assigned ID pointers in preview scene */
preview_prepare_scene(Main * bmain,Scene * scene,ID * id,int id_type,ShaderPreview * sp)367 static Scene *preview_prepare_scene(
368     Main *bmain, Scene *scene, ID *id, int id_type, ShaderPreview *sp)
369 {
370   Scene *sce;
371   Main *pr_main = sp->pr_main;
372 
373   memcpy(pr_main->name, BKE_main_blendfile_path(bmain), sizeof(pr_main->name));
374 
375   sce = preview_get_scene(pr_main);
376   if (sce) {
377     ViewLayer *view_layer = sce->view_layers.first;
378 
379     /* Only enable the combined renderpass */
380     view_layer->passflag = SCE_PASS_COMBINED;
381     view_layer->eevee.render_passes = 0;
382 
383     /* this flag tells render to not execute depsgraph or ipos etc */
384     sce->r.scemode |= R_BUTS_PREVIEW;
385     /* set world always back, is used now */
386     sce->world = pr_main->worlds.first;
387     /* now: exposure copy */
388     if (scene->world) {
389       sce->world->exp = scene->world->exp;
390       sce->world->range = scene->world->range;
391     }
392 
393     sce->r.color_mgt_flag = scene->r.color_mgt_flag;
394     BKE_color_managed_display_settings_copy(&sce->display_settings, &scene->display_settings);
395 
396     BKE_color_managed_view_settings_free(&sce->view_settings);
397     BKE_color_managed_view_settings_copy(&sce->view_settings, &scene->view_settings);
398 
399     /* prevent overhead for small renders and icons (32) */
400     if (id && sp->sizex < 40) {
401       sce->r.tilex = sce->r.tiley = 64;
402     }
403     else {
404       sce->r.tilex = sce->r.xsch / 4;
405       sce->r.tiley = sce->r.ysch / 4;
406     }
407 
408     if ((id && sp->pr_method == PR_ICON_RENDER) && id_type != ID_WO) {
409       sce->r.alphamode = R_ALPHAPREMUL;
410     }
411     else {
412       sce->r.alphamode = R_ADDSKY;
413     }
414 
415     sce->r.cfra = scene->r.cfra;
416 
417     if (id_type == ID_TE) {
418       /* Texture is not actually rendered with engine, just set dummy value. */
419       BLI_strncpy(sce->r.engine, RE_engine_id_BLENDER_EEVEE, sizeof(sce->r.engine));
420     }
421     else {
422       BLI_strncpy(sce->r.engine, scene->r.engine, sizeof(sce->r.engine));
423     }
424 
425     if (id_type == ID_MA) {
426       Material *mat = NULL, *origmat = (Material *)id;
427 
428       if (origmat) {
429         /* work on a copy */
430         BLI_assert(sp->id_copy != NULL);
431         mat = sp->matcopy = (Material *)sp->id_copy;
432         sp->id_copy = NULL;
433         BLI_addtail(&pr_main->materials, mat);
434 
435         /* Use current scene world for lighting. */
436         if (mat->pr_flag == MA_PREVIEW_WORLD && sp->pr_method == PR_BUTS_RENDER) {
437           /* Use current scene world to light sphere. */
438           sce->world = preview_get_localized_world(sp, scene->world);
439         }
440         else if (sce->world) {
441           /* Use a default world color. Using the current
442            * scene world can be slow if it has big textures. */
443           sce->world->use_nodes = false;
444           sce->world->horr = 0.05f;
445           sce->world->horg = 0.05f;
446           sce->world->horb = 0.05f;
447         }
448 
449         if (sp->pr_method == PR_ICON_RENDER && sp->pr_main == G_pr_main_grease_pencil) {
450           /* For grease pencil, always use sphere for icon renders. */
451           set_preview_visibility(sce, view_layer, MA_SPHERE_A, sp->pr_method);
452         }
453         else {
454           /* Use specified preview shape for both preview panel and icon previews. */
455           set_preview_visibility(sce, view_layer, mat->pr_type, sp->pr_method);
456         }
457 
458         if (sp->pr_method != PR_ICON_RENDER) {
459           if (mat->nodetree && sp->pr_method == PR_NODE_RENDER) {
460             /* two previews, they get copied by wmJob */
461             BKE_node_preview_init_tree(mat->nodetree, sp->sizex, sp->sizey, true);
462             /* WATCH: Accessing origmat is not safe! */
463             BKE_node_preview_init_tree(origmat->nodetree, sp->sizex, sp->sizey, true);
464           }
465         }
466       }
467       else {
468         sce->display.render_aa = SCE_DISPLAY_AA_OFF;
469       }
470 
471       LISTBASE_FOREACH (Base *, base, &view_layer->object_bases) {
472         if (base->object->id.name[2] == 'p') {
473           /* copy over object color, in case material uses it */
474           copy_v4_v4(base->object->color, sp->color);
475 
476           if (OB_TYPE_SUPPORT_MATERIAL(base->object->type)) {
477             /* don't use BKE_object_material_assign, it changed mat->id.us, which shows in the UI
478              */
479             Material ***matar = BKE_object_material_array_p(base->object);
480             int actcol = max_ii(base->object->actcol - 1, 0);
481 
482             if (matar && actcol < base->object->totcol) {
483               (*matar)[actcol] = mat;
484             }
485           }
486           else if (base->object->type == OB_LAMP) {
487             base->flag |= BASE_VISIBLE_DEPSGRAPH;
488           }
489         }
490       }
491     }
492     else if (id_type == ID_TE) {
493       Tex *tex = NULL, *origtex = (Tex *)id;
494 
495       if (origtex) {
496         BLI_assert(sp->id_copy != NULL);
497         tex = sp->texcopy = (Tex *)sp->id_copy;
498         sp->id_copy = NULL;
499         BLI_addtail(&pr_main->textures, tex);
500       }
501 
502       if (tex && tex->nodetree && sp->pr_method == PR_NODE_RENDER) {
503         /* two previews, they get copied by wmJob */
504         BKE_node_preview_init_tree(tex->nodetree, sp->sizex, sp->sizey, true);
505         /* WATCH: Accessing origtex is not safe! */
506         BKE_node_preview_init_tree(origtex->nodetree, sp->sizex, sp->sizey, true);
507       }
508     }
509     else if (id_type == ID_LA) {
510       Light *la = NULL, *origla = (Light *)id;
511 
512       /* work on a copy */
513       if (origla) {
514         BLI_assert(sp->id_copy != NULL);
515         la = sp->lampcopy = (Light *)sp->id_copy;
516         sp->id_copy = NULL;
517         BLI_addtail(&pr_main->lights, la);
518       }
519 
520       set_preview_visibility(sce, view_layer, MA_LAMP, sp->pr_method);
521 
522       if (sce->world) {
523         /* Only use lighting from the light. */
524         sce->world->use_nodes = false;
525         sce->world->horr = 0.0f;
526         sce->world->horg = 0.0f;
527         sce->world->horb = 0.0f;
528       }
529 
530       LISTBASE_FOREACH (Base *, base, &view_layer->object_bases) {
531         if (base->object->id.name[2] == 'p') {
532           if (base->object->type == OB_LAMP) {
533             base->object->data = la;
534           }
535         }
536       }
537 
538       if (la && la->nodetree && sp->pr_method == PR_NODE_RENDER) {
539         /* two previews, they get copied by wmJob */
540         BKE_node_preview_init_tree(la->nodetree, sp->sizex, sp->sizey, true);
541         /* WATCH: Accessing origla is not safe! */
542         BKE_node_preview_init_tree(origla->nodetree, sp->sizex, sp->sizey, true);
543       }
544     }
545     else if (id_type == ID_WO) {
546       World *wrld = NULL, *origwrld = (World *)id;
547 
548       if (origwrld) {
549         BLI_assert(sp->id_copy != NULL);
550         wrld = sp->worldcopy = (World *)sp->id_copy;
551         sp->id_copy = NULL;
552         BLI_addtail(&pr_main->worlds, wrld);
553       }
554 
555       set_preview_visibility(sce, view_layer, MA_SKY, sp->pr_method);
556       sce->world = wrld;
557 
558       if (wrld && wrld->nodetree && sp->pr_method == PR_NODE_RENDER) {
559         /* two previews, they get copied by wmJob */
560         BKE_node_preview_init_tree(wrld->nodetree, sp->sizex, sp->sizey, true);
561         /* WATCH: Accessing origwrld is not safe! */
562         BKE_node_preview_init_tree(origwrld->nodetree, sp->sizex, sp->sizey, true);
563       }
564     }
565 
566     return sce;
567   }
568 
569   return NULL;
570 }
571 
572 /* new UI convention: draw is in pixel space already. */
573 /* uses UI_BTYPE_ROUNDBOX button in block to get the rect */
ed_preview_draw_rect(ScrArea * area,int split,int first,rcti * rect,rcti * newrect)574 static bool ed_preview_draw_rect(ScrArea *area, int split, int first, rcti *rect, rcti *newrect)
575 {
576   Render *re;
577   RenderView *rv;
578   RenderResult rres;
579   char name[32];
580   int offx = 0;
581   int newx = BLI_rcti_size_x(rect);
582   int newy = BLI_rcti_size_y(rect);
583   bool ok = false;
584 
585   if (!split || first) {
586     sprintf(name, "Preview %p", (void *)area);
587   }
588   else {
589     sprintf(name, "SecondPreview %p", (void *)area);
590   }
591 
592   if (split) {
593     if (first) {
594       offx = 0;
595       newx = newx / 2;
596     }
597     else {
598       offx = newx / 2;
599       newx = newx - newx / 2;
600     }
601   }
602 
603   /* test if something rendered ok */
604   re = RE_GetRender(name);
605 
606   if (re == NULL) {
607     return false;
608   }
609 
610   RE_AcquireResultImageViews(re, &rres);
611 
612   if (!BLI_listbase_is_empty(&rres.views)) {
613     /* material preview only needs monoscopy (view 0) */
614     rv = RE_RenderViewGetById(&rres, 0);
615   }
616   else {
617     /* possible the job clears the views but we're still drawing T45496 */
618     rv = NULL;
619   }
620 
621   if (rv && rv->rectf) {
622 
623     if (abs(rres.rectx - newx) < 2 && abs(rres.recty - newy) < 2) {
624 
625       newrect->xmax = max_ii(newrect->xmax, rect->xmin + rres.rectx + offx);
626       newrect->ymax = max_ii(newrect->ymax, rect->ymin + rres.recty);
627 
628       if (rres.rectx && rres.recty) {
629         uchar *rect_byte = MEM_mallocN(rres.rectx * rres.recty * sizeof(int),
630                                        "ed_preview_draw_rect");
631         float fx = rect->xmin + offx;
632         float fy = rect->ymin;
633 
634         /* material preview only needs monoscopy (view 0) */
635         if (re) {
636           RE_AcquiredResultGet32(re, &rres, (uint *)rect_byte, 0);
637         }
638 
639         IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);
640         immDrawPixelsTex(
641             &state, fx, fy, rres.rectx, rres.recty, GPU_RGBA8, false, rect_byte, 1.0f, 1.0f, NULL);
642 
643         MEM_freeN(rect_byte);
644 
645         ok = 1;
646       }
647     }
648   }
649 
650   RE_ReleaseResultImageViews(re, &rres);
651 
652   return ok;
653 }
654 
ED_preview_draw(const bContext * C,void * idp,void * parentp,void * slotp,rcti * rect)655 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
656 {
657   if (idp) {
658     wmWindowManager *wm = CTX_wm_manager(C);
659     ScrArea *area = CTX_wm_area(C);
660     ID *id = (ID *)idp;
661     ID *parent = (ID *)parentp;
662     MTex *slot = (MTex *)slotp;
663     SpaceProperties *sbuts = CTX_wm_space_properties(C);
664     ShaderPreview *sp = WM_jobs_customdata(wm, area);
665     rcti newrect;
666     int ok;
667     int newx = BLI_rcti_size_x(rect);
668     int newy = BLI_rcti_size_y(rect);
669 
670     newrect.xmin = rect->xmin;
671     newrect.xmax = rect->xmin;
672     newrect.ymin = rect->ymin;
673     newrect.ymax = rect->ymin;
674 
675     if (parent) {
676       ok = ed_preview_draw_rect(area, 1, 1, rect, &newrect);
677       ok &= ed_preview_draw_rect(area, 1, 0, rect, &newrect);
678     }
679     else {
680       ok = ed_preview_draw_rect(area, 0, 0, rect, &newrect);
681     }
682 
683     if (ok) {
684       *rect = newrect;
685     }
686 
687     /* start a new preview render job if signaled through sbuts->preview,
688      * if no render result was found and no preview render job is running,
689      * or if the job is running and the size of preview changed */
690     if ((sbuts != NULL && sbuts->preview) ||
691         (!ok && !WM_jobs_test(wm, area, WM_JOB_TYPE_RENDER_PREVIEW)) ||
692         (sp && (abs(sp->sizex - newx) >= 2 || abs(sp->sizey - newy) > 2))) {
693       if (sbuts != NULL) {
694         sbuts->preview = 0;
695       }
696       ED_preview_shader_job(C, area, id, parent, slot, newx, newy, PR_BUTS_RENDER);
697     }
698   }
699 }
700 
701 /* **************************** new shader preview system ****************** */
702 
703 /* inside thread, called by renderer, sets job update value */
shader_preview_update(void * spv,RenderResult * UNUSED (rr),volatile struct rcti * UNUSED (rect))704 static void shader_preview_update(void *spv,
705                                   RenderResult *UNUSED(rr),
706                                   volatile struct rcti *UNUSED(rect))
707 {
708   ShaderPreview *sp = spv;
709 
710   *(sp->do_update) = true;
711 }
712 
713 /* called by renderer, checks job value */
shader_preview_break(void * spv)714 static int shader_preview_break(void *spv)
715 {
716   ShaderPreview *sp = spv;
717 
718   return *(sp->stop);
719 }
720 
721 /* outside thread, called before redraw notifiers, it moves finished preview over */
shader_preview_updatejob(void * spv)722 static void shader_preview_updatejob(void *spv)
723 {
724   ShaderPreview *sp = spv;
725 
726   if (sp->pr_method == PR_NODE_RENDER) {
727     if (GS(sp->id->name) == ID_MA) {
728       Material *mat = (Material *)sp->id;
729 
730       if (sp->matcopy && mat->nodetree && sp->matcopy->nodetree) {
731         ntreeLocalSync(sp->matcopy->nodetree, mat->nodetree);
732       }
733     }
734     else if (GS(sp->id->name) == ID_TE) {
735       Tex *tex = (Tex *)sp->id;
736 
737       if (sp->texcopy && tex->nodetree && sp->texcopy->nodetree) {
738         ntreeLocalSync(sp->texcopy->nodetree, tex->nodetree);
739       }
740     }
741     else if (GS(sp->id->name) == ID_WO) {
742       World *wrld = (World *)sp->id;
743 
744       if (sp->worldcopy && wrld->nodetree && sp->worldcopy->nodetree) {
745         ntreeLocalSync(sp->worldcopy->nodetree, wrld->nodetree);
746       }
747     }
748     else if (GS(sp->id->name) == ID_LA) {
749       Light *la = (Light *)sp->id;
750 
751       if (sp->lampcopy && la->nodetree && sp->lampcopy->nodetree) {
752         ntreeLocalSync(sp->lampcopy->nodetree, la->nodetree);
753       }
754     }
755   }
756 }
757 
758 /* Renders texture directly to render buffer. */
shader_preview_texture(ShaderPreview * sp,Tex * tex,Scene * sce,Render * re)759 static void shader_preview_texture(ShaderPreview *sp, Tex *tex, Scene *sce, Render *re)
760 {
761   /* Setup output buffer. */
762   int width = sp->sizex;
763   int height = sp->sizey;
764 
765   /* This is needed otherwise no RenderResult is created. */
766   sce->r.scemode &= ~R_BUTS_PREVIEW;
767   RE_InitState(re, NULL, &sce->r, &sce->view_layers, NULL, width, height, NULL);
768   RE_SetScene(re, sce);
769 
770   /* Create buffer in empty RenderView created in the init step. */
771   RenderResult *rr = RE_AcquireResultWrite(re);
772   RenderView *rv = (RenderView *)rr->views.first;
773   rv->rectf = MEM_callocN(sizeof(float[4]) * width * height, "texture render result");
774   RE_ReleaseResult(re);
775 
776   /* Get texture image pool (if any) */
777   struct ImagePool *img_pool = BKE_image_pool_new();
778   BKE_texture_fetch_images_for_pool(tex, img_pool);
779 
780   /* Fill in image buffer. */
781   float *rect_float = rv->rectf;
782   float tex_coord[3] = {0.0f, 0.0f, 0.0f};
783   bool color_manage = true;
784 
785   for (int y = 0; y < height; y++) {
786     /* Tex coords between -1.0f and 1.0f. */
787     tex_coord[1] = ((float)y / (float)height) * 2.0f - 1.0f;
788 
789     for (int x = 0; x < width; x++) {
790       tex_coord[0] = ((float)x / (float)height) * 2.0f - 1.0f;
791 
792       /* Evaluate texture at tex_coord .*/
793       TexResult texres = {0};
794       BKE_texture_get_value_ex(sce, tex, tex_coord, &texres, img_pool, color_manage);
795 
796       rect_float[0] = texres.tr;
797       rect_float[1] = texres.tg;
798       rect_float[2] = texres.tb;
799       rect_float[3] = texres.talpha ? texres.ta : 1.0f;
800 
801       rect_float += 4;
802     }
803 
804     /* Check if we should cancel texture preview. */
805     if (shader_preview_break(sp)) {
806       break;
807     }
808   }
809 
810   BKE_image_pool_free(img_pool);
811 }
812 
shader_preview_render(ShaderPreview * sp,ID * id,int split,int first)813 static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int first)
814 {
815   Render *re;
816   Scene *sce;
817   float oldlens;
818   short idtype = GS(id->name);
819   char name[32];
820   int sizex;
821   Main *pr_main = sp->pr_main;
822 
823   /* in case of split preview, use border render */
824   if (split) {
825     if (first) {
826       sizex = sp->sizex / 2;
827     }
828     else {
829       sizex = sp->sizex - sp->sizex / 2;
830     }
831   }
832   else {
833     sizex = sp->sizex;
834   }
835 
836   /* we have to set preview variables first */
837   sce = preview_get_scene(pr_main);
838   if (sce) {
839     sce->r.xsch = sizex;
840     sce->r.ysch = sp->sizey;
841     sce->r.size = 100;
842   }
843 
844   /* get the stuff from the builtin preview dbase */
845   sce = preview_prepare_scene(sp->bmain, sp->scene, id, idtype, sp);
846   if (sce == NULL) {
847     return;
848   }
849 
850   if (!split || first) {
851     sprintf(name, "Preview %p", sp->owner);
852   }
853   else {
854     sprintf(name, "SecondPreview %p", sp->owner);
855   }
856   re = RE_GetRender(name);
857 
858   /* full refreshed render from first tile */
859   if (re == NULL) {
860     re = RE_NewRender(name);
861   }
862 
863   /* sce->r gets copied in RE_InitState! */
864   sce->r.scemode &= ~(R_MATNODE_PREVIEW | R_TEXNODE_PREVIEW);
865   sce->r.scemode &= ~R_NO_IMAGE_LOAD;
866 
867   if (sp->pr_method == PR_ICON_RENDER) {
868     sce->r.scemode |= R_NO_IMAGE_LOAD;
869     sce->display.render_aa = SCE_DISPLAY_AA_SAMPLES_8;
870   }
871   else if (sp->pr_method == PR_NODE_RENDER) {
872     if (idtype == ID_MA) {
873       sce->r.scemode |= R_MATNODE_PREVIEW;
874     }
875     else if (idtype == ID_TE) {
876       sce->r.scemode |= R_TEXNODE_PREVIEW;
877     }
878     sce->display.render_aa = SCE_DISPLAY_AA_OFF;
879   }
880   else { /* PR_BUTS_RENDER */
881     sce->display.render_aa = SCE_DISPLAY_AA_SAMPLES_8;
882   }
883 
884   /* Callbacks are cleared on GetRender(). */
885   if (ELEM(sp->pr_method, PR_BUTS_RENDER, PR_NODE_RENDER)) {
886     RE_display_update_cb(re, sp, shader_preview_update);
887   }
888   /* set this for all previews, default is react to G.is_break still */
889   RE_test_break_cb(re, sp, shader_preview_break);
890 
891   /* lens adjust */
892   oldlens = ((Camera *)sce->camera->data)->lens;
893   if (sizex > sp->sizey) {
894     ((Camera *)sce->camera->data)->lens *= (float)sp->sizey / (float)sizex;
895   }
896 
897   /* entire cycle for render engine */
898   if (idtype == ID_TE) {
899     shader_preview_texture(sp, (Tex *)id, sce, re);
900   }
901   else {
902     /* Render preview scene */
903     RE_PreviewRender(re, pr_main, sce);
904   }
905 
906   ((Camera *)sce->camera->data)->lens = oldlens;
907 
908   /* handle results */
909   if (sp->pr_method == PR_ICON_RENDER) {
910     // char *rct = (char *)(sp->pr_rect + 32 * 16 + 16);
911 
912     if (sp->pr_rect) {
913       RE_ResultGet32(re, sp->pr_rect);
914     }
915   }
916 
917   /* unassign the pointers, reset vars */
918   preview_prepare_scene(sp->bmain, sp->scene, NULL, GS(id->name), sp);
919 
920   /* XXX bad exception, end-exec is not being called in render, because it uses local main. */
921 #if 0
922   if (idtype == ID_TE) {
923     Tex *tex = (Tex *)id;
924     if (tex->use_nodes && tex->nodetree)
925       ntreeEndExecTree(tex->nodetree);
926   }
927 #endif
928 }
929 
930 /* runs inside thread for material and icons */
shader_preview_startjob(void * customdata,short * stop,short * do_update)931 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
932 {
933   ShaderPreview *sp = customdata;
934 
935   sp->stop = stop;
936   sp->do_update = do_update;
937 
938   if (sp->parent) {
939     shader_preview_render(sp, sp->id, 1, 1);
940     shader_preview_render(sp, sp->parent, 1, 0);
941   }
942   else {
943     shader_preview_render(sp, sp->id, 0, 0);
944   }
945 
946   *do_update = true;
947 }
948 
preview_id_copy_free(ID * id)949 static void preview_id_copy_free(ID *id)
950 {
951   struct IDProperty *properties;
952   /* get rid of copied ID */
953   properties = IDP_GetProperties(id, false);
954   if (properties) {
955     IDP_FreePropertyContent_ex(properties, false);
956     MEM_freeN(properties);
957   }
958   BKE_libblock_free_datablock(id, 0);
959   MEM_freeN(id);
960 }
961 
shader_preview_free(void * customdata)962 static void shader_preview_free(void *customdata)
963 {
964   ShaderPreview *sp = customdata;
965   Main *pr_main = sp->pr_main;
966   ID *main_id_copy = NULL;
967   ID *sub_id_copy = NULL;
968 
969   if (sp->matcopy) {
970     main_id_copy = (ID *)sp->matcopy;
971     BLI_remlink(&pr_main->materials, sp->matcopy);
972   }
973   if (sp->texcopy) {
974     BLI_assert(main_id_copy == NULL);
975     main_id_copy = (ID *)sp->texcopy;
976     BLI_remlink(&pr_main->textures, sp->texcopy);
977   }
978   if (sp->worldcopy) {
979     /* worldcopy is also created for material with `Preview World` enabled */
980     if (main_id_copy) {
981       sub_id_copy = (ID *)sp->worldcopy;
982     }
983     else {
984       main_id_copy = (ID *)sp->worldcopy;
985     }
986     BLI_remlink(&pr_main->worlds, sp->worldcopy);
987   }
988   if (sp->lampcopy) {
989     BLI_assert(main_id_copy == NULL);
990     main_id_copy = (ID *)sp->lampcopy;
991     BLI_remlink(&pr_main->lights, sp->lampcopy);
992   }
993   if (main_id_copy || sp->id_copy) {
994     /* node previews */
995     shader_preview_updatejob(sp);
996   }
997   if (sp->own_id_copy) {
998     if (sp->id_copy) {
999       preview_id_copy_free(sp->id_copy);
1000     }
1001     if (main_id_copy) {
1002       preview_id_copy_free(main_id_copy);
1003     }
1004     if (sub_id_copy) {
1005       preview_id_copy_free(sub_id_copy);
1006     }
1007   }
1008 
1009   MEM_freeN(sp);
1010 }
1011 
1012 /* ************************* icon preview ********************** */
1013 
icon_copy_rect(ImBuf * ibuf,uint w,uint h,uint * rect)1014 static void icon_copy_rect(ImBuf *ibuf, uint w, uint h, uint *rect)
1015 {
1016   struct ImBuf *ima;
1017   uint *drect, *srect;
1018   float scaledx, scaledy;
1019   short ex, ey, dx, dy;
1020 
1021   /* paranoia test */
1022   if (ibuf == NULL || (ibuf->rect == NULL && ibuf->rect_float == NULL)) {
1023     return;
1024   }
1025 
1026   /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
1027   ima = IMB_dupImBuf(ibuf);
1028 
1029   if (!ima) {
1030     return;
1031   }
1032 
1033   if (ima->x > ima->y) {
1034     scaledx = (float)w;
1035     scaledy = ((float)ima->y / (float)ima->x) * (float)w;
1036   }
1037   else {
1038     scaledx = ((float)ima->x / (float)ima->y) * (float)h;
1039     scaledy = (float)h;
1040   }
1041 
1042   ex = (short)scaledx;
1043   ey = (short)scaledy;
1044 
1045   dx = (w - ex) / 2;
1046   dy = (h - ey) / 2;
1047 
1048   IMB_scalefastImBuf(ima, ex, ey);
1049 
1050   /* if needed, convert to 32 bits */
1051   if (ima->rect == NULL) {
1052     IMB_rect_from_float(ima);
1053   }
1054 
1055   srect = ima->rect;
1056   drect = rect;
1057 
1058   drect += dy * w + dx;
1059   for (; ey > 0; ey--) {
1060     memcpy(drect, srect, ex * sizeof(int));
1061     drect += w;
1062     srect += ima->x;
1063   }
1064 
1065   IMB_freeImBuf(ima);
1066 }
1067 
set_alpha(char * cp,int sizex,int sizey,char alpha)1068 static void set_alpha(char *cp, int sizex, int sizey, char alpha)
1069 {
1070   int a, size = sizex * sizey;
1071 
1072   for (a = 0; a < size; a++, cp += 4) {
1073     cp[3] = alpha;
1074   }
1075 }
1076 
icon_preview_startjob(void * customdata,short * stop,short * do_update)1077 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
1078 {
1079   ShaderPreview *sp = customdata;
1080 
1081   if (sp->pr_method == PR_ICON_DEFERRED) {
1082     PreviewImage *prv = sp->owner;
1083     ImBuf *thumb;
1084     char *deferred_data = PRV_DEFERRED_DATA(prv);
1085     int source = deferred_data[0];
1086     char *path = &deferred_data[1];
1087 
1088     // printf("generating deferred %d×%d preview for %s\n", sp->sizex, sp->sizey, path);
1089 
1090     thumb = IMB_thumb_manage(path, THB_LARGE, source);
1091 
1092     if (thumb) {
1093       /* PreviewImage assumes premultiplied alhpa... */
1094       IMB_premultiply_alpha(thumb);
1095 
1096       icon_copy_rect(thumb, sp->sizex, sp->sizey, sp->pr_rect);
1097       IMB_freeImBuf(thumb);
1098     }
1099   }
1100   else {
1101     ID *id = sp->id;
1102     short idtype = GS(id->name);
1103 
1104     if (idtype == ID_IM) {
1105       Image *ima = (Image *)id;
1106       ImBuf *ibuf = NULL;
1107       ImageUser iuser;
1108       BKE_imageuser_default(&iuser);
1109 
1110       if (ima == NULL) {
1111         return;
1112       }
1113 
1114       ImageTile *tile = BKE_image_get_tile(ima, 0);
1115       /* tile->ok is zero when Image cannot load */
1116       if (tile->ok == 0) {
1117         return;
1118       }
1119 
1120       /* setup dummy image user */
1121       iuser.ok = iuser.framenr = 1;
1122       iuser.scene = sp->scene;
1123 
1124       /* elubie: this needs to be changed: here image is always loaded if not
1125        * already there. Very expensive for large images. Need to find a way to
1126        * only get existing ibuf */
1127       ibuf = BKE_image_acquire_ibuf(ima, &iuser, NULL);
1128       if (ibuf == NULL || ibuf->rect == NULL) {
1129         BKE_image_release_ibuf(ima, ibuf, NULL);
1130         return;
1131       }
1132 
1133       icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
1134 
1135       *do_update = true;
1136 
1137       BKE_image_release_ibuf(ima, ibuf, NULL);
1138     }
1139     else if (idtype == ID_BR) {
1140       Brush *br = (Brush *)id;
1141 
1142       br->icon_imbuf = get_brush_icon(br);
1143 
1144       memset(sp->pr_rect, 0x88, sp->sizex * sp->sizey * sizeof(uint));
1145 
1146       if (!(br->icon_imbuf) || !(br->icon_imbuf->rect)) {
1147         return;
1148       }
1149 
1150       icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
1151 
1152       *do_update = true;
1153     }
1154     else if (idtype == ID_SCR) {
1155       bScreen *screen = (bScreen *)id;
1156 
1157       ED_screen_preview_render(screen, sp->sizex, sp->sizey, sp->pr_rect);
1158       *do_update = true;
1159     }
1160     else {
1161       /* re-use shader job */
1162       shader_preview_startjob(customdata, stop, do_update);
1163 
1164       /* world is rendered with alpha=0, so it wasn't displayed
1165        * this could be render option for sky to, for later */
1166       if (idtype == ID_WO) {
1167         set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
1168       }
1169     }
1170   }
1171 }
1172 
1173 /* use same function for icon & shader, so the job manager
1174  * does not run two of them at the same time. */
1175 
common_preview_startjob(void * customdata,short * stop,short * do_update,float * UNUSED (progress))1176 static void common_preview_startjob(void *customdata,
1177                                     short *stop,
1178                                     short *do_update,
1179                                     float *UNUSED(progress))
1180 {
1181   ShaderPreview *sp = customdata;
1182 
1183   if (ELEM(sp->pr_method, PR_ICON_RENDER, PR_ICON_DEFERRED)) {
1184     icon_preview_startjob(customdata, stop, do_update);
1185   }
1186   else {
1187     shader_preview_startjob(customdata, stop, do_update);
1188   }
1189 }
1190 
1191 /* exported functions */
1192 
icon_preview_add_size(IconPreview * ip,uint * rect,int sizex,int sizey)1193 static void icon_preview_add_size(IconPreview *ip, uint *rect, int sizex, int sizey)
1194 {
1195   IconPreviewSize *cur_size = ip->sizes.first, *new_size;
1196 
1197   while (cur_size) {
1198     if (cur_size->sizex == sizex && cur_size->sizey == sizey) {
1199       /* requested size is already in list, no need to add it again */
1200       return;
1201     }
1202 
1203     cur_size = cur_size->next;
1204   }
1205 
1206   new_size = MEM_callocN(sizeof(IconPreviewSize), "IconPreviewSize");
1207   new_size->sizex = sizex;
1208   new_size->sizey = sizey;
1209   new_size->rect = rect;
1210 
1211   BLI_addtail(&ip->sizes, new_size);
1212 }
1213 
icon_preview_startjob_all_sizes(void * customdata,short * stop,short * do_update,float * progress)1214 static void icon_preview_startjob_all_sizes(void *customdata,
1215                                             short *stop,
1216                                             short *do_update,
1217                                             float *progress)
1218 {
1219   IconPreview *ip = (IconPreview *)customdata;
1220   IconPreviewSize *cur_size;
1221 
1222   for (cur_size = ip->sizes.first; cur_size; cur_size = cur_size->next) {
1223     PreviewImage *prv = ip->owner;
1224 
1225     if (*stop) {
1226       break;
1227     }
1228 
1229     if (prv->tag & PRV_TAG_DEFFERED_DELETE) {
1230       /* Non-thread-protected reading is not an issue here. */
1231       continue;
1232     }
1233 
1234     if (!check_engine_supports_preview(ip->scene)) {
1235       continue;
1236     }
1237 
1238     ShaderPreview *sp = MEM_callocN(sizeof(ShaderPreview), "Icon ShaderPreview");
1239     const bool is_render = !(prv->tag & PRV_TAG_DEFFERED);
1240 
1241     /* construct shader preview from image size and previewcustomdata */
1242     sp->scene = ip->scene;
1243     sp->owner = ip->owner;
1244     sp->sizex = cur_size->sizex;
1245     sp->sizey = cur_size->sizey;
1246     sp->pr_method = is_render ? PR_ICON_RENDER : PR_ICON_DEFERRED;
1247     sp->pr_rect = cur_size->rect;
1248     sp->id = ip->id;
1249     sp->id_copy = ip->id_copy;
1250     sp->bmain = ip->bmain;
1251     sp->own_id_copy = false;
1252     Material *ma = NULL;
1253 
1254     if (is_render) {
1255       BLI_assert(ip->id);
1256 
1257       /* grease pencil use its own preview file */
1258       if (GS(ip->id->name) == ID_MA) {
1259         ma = (Material *)ip->id;
1260       }
1261 
1262       if ((ma == NULL) || (ma->gp_style == NULL)) {
1263         sp->pr_main = G_pr_main;
1264       }
1265       else {
1266         sp->pr_main = G_pr_main_grease_pencil;
1267       }
1268     }
1269 
1270     common_preview_startjob(sp, stop, do_update, progress);
1271     shader_preview_free(sp);
1272   }
1273 }
1274 
icon_preview_endjob(void * customdata)1275 static void icon_preview_endjob(void *customdata)
1276 {
1277   IconPreview *ip = customdata;
1278 
1279   if (ip->id) {
1280 
1281     if (GS(ip->id->name) == ID_BR) {
1282       WM_main_add_notifier(NC_BRUSH | NA_EDITED, ip->id);
1283     }
1284 #if 0
1285     if (GS(ip->id->name) == ID_MA) {
1286       Material *ma = (Material *)ip->id;
1287       PreviewImage *prv_img = ma->preview;
1288       int i;
1289 
1290       /* signal to gpu texture */
1291       for (i = 0; i < NUM_ICON_SIZES; i++) {
1292         if (prv_img->gputexture[i]) {
1293           GPU_texture_free(prv_img->gputexture[i]);
1294           prv_img->gputexture[i] = NULL;
1295           WM_main_add_notifier(NC_MATERIAL | ND_SHADING_DRAW, ip->id);
1296         }
1297       }
1298     }
1299 #endif
1300   }
1301 
1302   if (ip->owner) {
1303     PreviewImage *prv_img = ip->owner;
1304     prv_img->tag &= ~PRV_TAG_DEFFERED_RENDERING;
1305     if (prv_img->tag & PRV_TAG_DEFFERED_DELETE) {
1306       BLI_assert(prv_img->tag & PRV_TAG_DEFFERED);
1307       BKE_previewimg_cached_release_pointer(prv_img);
1308     }
1309   }
1310 }
1311 
icon_preview_free(void * customdata)1312 static void icon_preview_free(void *customdata)
1313 {
1314   IconPreview *ip = (IconPreview *)customdata;
1315 
1316   if (ip->id_copy) {
1317     preview_id_copy_free(ip->id_copy);
1318   }
1319 
1320   BLI_freelistN(&ip->sizes);
1321   MEM_freeN(ip);
1322 }
1323 
ED_preview_icon_render(Main * bmain,Scene * scene,ID * id,uint * rect,int sizex,int sizey)1324 void ED_preview_icon_render(Main *bmain, Scene *scene, ID *id, uint *rect, int sizex, int sizey)
1325 {
1326   IconPreview ip = {NULL};
1327   short stop = false, update = false;
1328   float progress = 0.0f;
1329 
1330   ED_preview_ensure_dbase();
1331 
1332   ip.bmain = bmain;
1333   ip.scene = scene;
1334   ip.owner = BKE_previewimg_id_ensure(id);
1335   ip.id = id;
1336   ip.id_copy = duplicate_ids(id);
1337 
1338   icon_preview_add_size(&ip, rect, sizex, sizey);
1339 
1340   icon_preview_startjob_all_sizes(&ip, &stop, &update, &progress);
1341 
1342   icon_preview_endjob(&ip);
1343 
1344   BLI_freelistN(&ip.sizes);
1345   if (ip.id_copy != NULL) {
1346     preview_id_copy_free(ip.id_copy);
1347   }
1348 }
1349 
ED_preview_icon_job(const bContext * C,void * owner,ID * id,uint * rect,int sizex,int sizey,const bool delay)1350 void ED_preview_icon_job(
1351     const bContext *C, void *owner, ID *id, uint *rect, int sizex, int sizey, const bool delay)
1352 {
1353   wmJob *wm_job;
1354   IconPreview *ip, *old_ip;
1355 
1356   ED_preview_ensure_dbase();
1357 
1358   /* suspended start means it starts after 1 timer step, see WM_jobs_timer below */
1359   wm_job = WM_jobs_get(CTX_wm_manager(C),
1360                        CTX_wm_window(C),
1361                        owner,
1362                        "Icon Preview",
1363                        WM_JOB_EXCL_RENDER,
1364                        WM_JOB_TYPE_RENDER_PREVIEW);
1365 
1366   ip = MEM_callocN(sizeof(IconPreview), "icon preview");
1367 
1368   /* render all resolutions from suspended job too */
1369   old_ip = WM_jobs_customdata_get(wm_job);
1370   if (old_ip) {
1371     BLI_movelisttolist(&ip->sizes, &old_ip->sizes);
1372   }
1373 
1374   /* customdata for preview thread */
1375   ip->bmain = CTX_data_main(C);
1376   ip->scene = CTX_data_scene(C);
1377   ip->owner = owner;
1378   ip->id = id;
1379   ip->id_copy = duplicate_ids(id);
1380 
1381   icon_preview_add_size(ip, rect, sizex, sizey);
1382 
1383   /* Special threading hack:
1384    * warn main code that this preview is being rendered and cannot be freed... */
1385   {
1386     PreviewImage *prv_img = owner;
1387     if (prv_img->tag & PRV_TAG_DEFFERED) {
1388       prv_img->tag |= PRV_TAG_DEFFERED_RENDERING;
1389     }
1390   }
1391 
1392   /* setup job */
1393   WM_jobs_customdata_set(wm_job, ip, icon_preview_free);
1394   WM_jobs_timer(wm_job, 0.1, NC_WINDOW, NC_WINDOW);
1395   /* Wait 2s to start rendering icon previews, to not bog down user interaction.
1396    * Particularly important for heavy scenes and Eevee using OpenGL that blocks
1397    * the user interface drawing. */
1398   WM_jobs_delay_start(wm_job, (delay) ? 2.0 : 0.0);
1399   WM_jobs_callbacks(wm_job, icon_preview_startjob_all_sizes, NULL, NULL, icon_preview_endjob);
1400 
1401   WM_jobs_start(CTX_wm_manager(C), wm_job);
1402 }
1403 
ED_preview_shader_job(const bContext * C,void * owner,ID * id,ID * parent,MTex * slot,int sizex,int sizey,int method)1404 void ED_preview_shader_job(const bContext *C,
1405                            void *owner,
1406                            ID *id,
1407                            ID *parent,
1408                            MTex *slot,
1409                            int sizex,
1410                            int sizey,
1411                            int method)
1412 {
1413   Object *ob = CTX_data_active_object(C);
1414   wmJob *wm_job;
1415   ShaderPreview *sp;
1416   Scene *scene = CTX_data_scene(C);
1417   short id_type = GS(id->name);
1418 
1419   /* Use workspace render only for buttons Window,
1420    * since the other previews are related to the datablock. */
1421 
1422   if (!check_engine_supports_preview(scene)) {
1423     return;
1424   }
1425 
1426   /* Only texture node preview is supported with Cycles. */
1427   if (method == PR_NODE_RENDER && id_type != ID_TE) {
1428     return;
1429   }
1430 
1431   ED_preview_ensure_dbase();
1432 
1433   wm_job = WM_jobs_get(CTX_wm_manager(C),
1434                        CTX_wm_window(C),
1435                        owner,
1436                        "Shader Preview",
1437                        WM_JOB_EXCL_RENDER,
1438                        WM_JOB_TYPE_RENDER_PREVIEW);
1439   sp = MEM_callocN(sizeof(ShaderPreview), "shader preview");
1440 
1441   /* customdata for preview thread */
1442   sp->scene = scene;
1443   sp->owner = owner;
1444   sp->sizex = sizex;
1445   sp->sizey = sizey;
1446   sp->pr_method = method;
1447   sp->id = id;
1448   sp->id_copy = duplicate_ids(id);
1449   sp->own_id_copy = true;
1450   sp->parent = parent;
1451   sp->slot = slot;
1452   sp->bmain = CTX_data_main(C);
1453   Material *ma = NULL;
1454 
1455   /* hardcoded preview .blend for Eevee + Cycles, this should be solved
1456    * once with custom preview .blend path for external engines */
1457 
1458   /* grease pencil use its own preview file */
1459   if (GS(id->name) == ID_MA) {
1460     ma = (Material *)id;
1461   }
1462 
1463   if ((ma == NULL) || (ma->gp_style == NULL)) {
1464     sp->pr_main = G_pr_main;
1465   }
1466   else {
1467     sp->pr_main = G_pr_main_grease_pencil;
1468   }
1469 
1470   if (ob && ob->totcol) {
1471     copy_v4_v4(sp->color, ob->color);
1472   }
1473   else {
1474     ARRAY_SET_ITEMS(sp->color, 0.0f, 0.0f, 0.0f, 1.0f);
1475   }
1476 
1477   /* setup job */
1478   WM_jobs_customdata_set(wm_job, sp, shader_preview_free);
1479   WM_jobs_timer(wm_job, 0.1, NC_MATERIAL, NC_MATERIAL);
1480   WM_jobs_callbacks(wm_job, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
1481 
1482   WM_jobs_start(CTX_wm_manager(C), wm_job);
1483 }
1484 
ED_preview_kill_jobs(wmWindowManager * wm,Main * UNUSED (bmain))1485 void ED_preview_kill_jobs(wmWindowManager *wm, Main *UNUSED(bmain))
1486 {
1487   if (wm) {
1488     /* This is called to stop all preview jobs before scene data changes, to
1489      * avoid invalid memory access. */
1490     WM_jobs_kill(wm, NULL, common_preview_startjob);
1491     WM_jobs_kill(wm, NULL, icon_preview_startjob_all_sizes);
1492   }
1493 }
1494