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