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