Alpha premul pipeline cleanup
[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 "BLO_readfile.h" 
47
48 #include "BLI_math.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_threads.h"
51 #include "BLI_utildefines.h"
52
53 #include "DNA_world_types.h"
54 #include "DNA_camera_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_view3d_types.h"
61 #include "DNA_scene_types.h"
62 #include "DNA_brush_types.h"
63 #include "DNA_screen_types.h"
64
65 #include "BKE_brush.h"
66 #include "BKE_context.h"
67 #include "BKE_colortools.h"
68 #include "BKE_depsgraph.h"
69 #include "BKE_global.h"
70 #include "BKE_idprop.h"
71 #include "BKE_image.h"
72 #include "BKE_icons.h"
73 #include "BKE_lamp.h"
74 #include "BKE_library.h"
75 #include "BKE_main.h"
76 #include "BKE_material.h"
77 #include "BKE_node.h"
78 #include "BKE_object.h"
79 #include "BKE_scene.h"
80 #include "BKE_texture.h"
81 #include "BKE_world.h"
82
83 #include "IMB_imbuf.h"
84 #include "IMB_imbuf_types.h"
85 #include "IMB_colormanagement.h"
86
87 #include "BIF_gl.h"
88 #include "BIF_glutil.h"
89
90 #include "PIL_time.h"
91
92 #include "RE_pipeline.h"
93
94
95 #include "WM_api.h"
96 #include "WM_types.h"
97
98 #include "ED_render.h"
99 #include "ED_view3d.h"
100
101 #include "UI_interface.h"
102
103 #include "render_intern.h"
104
105 ImBuf *get_brush_icon(Brush *brush)
106 {
107         static const int flags = IB_rect | IB_multilayer | IB_metadata;
108
109         char path[FILE_MAX];
110         char *folder;
111
112         if (!(brush->icon_imbuf)) {
113                 if (brush->flag & BRUSH_CUSTOM_ICON) {
114
115                         if (brush->icon_filepath[0]) {
116                                 // first use the path directly to try and load the file
117
118                                 BLI_strncpy(path, brush->icon_filepath, sizeof(brush->icon_filepath));
119                                 BLI_path_abs(path, G.main->name);
120
121                                 /* use default colorspaces for brushes */
122                                 brush->icon_imbuf = IMB_loadiffname(path, flags, NULL);
123
124                                 // otherwise lets try to find it in other directories
125                                 if (!(brush->icon_imbuf)) {
126                                         folder = BLI_get_folder(BLENDER_DATAFILES, "brushicons");
127
128                                         BLI_make_file_string(G.main->name, path, folder, brush->icon_filepath);
129
130                                         if (path[0]) {
131                                                 /* use fefault color spaces */
132                                                 brush->icon_imbuf = IMB_loadiffname(path, flags, NULL);
133                                         }
134                                 }
135
136                                 if (brush->icon_imbuf)
137                                         BKE_icon_changed(BKE_icon_getid(&brush->id));
138                         }
139                 }
140         }
141
142         if (!(brush->icon_imbuf))
143                 brush->id.icon_id = 0;
144
145         return brush->icon_imbuf;
146 }
147
148 typedef struct ShaderPreview {
149         /* from wmJob */
150         void *owner;
151         short *stop, *do_update;
152         
153         Scene *scene;
154         ID *id;
155         ID *parent;
156         MTex *slot;
157         
158         /* datablocks with nodes need full copy during preview render, glsl uses it too */
159         Material *matcopy;
160         Tex *texcopy;
161         Lamp *lampcopy;
162         World *worldcopy;
163         
164         float col[4];       /* active object color */
165         
166         int sizex, sizey;
167         unsigned int *pr_rect;
168         int pr_method;
169         
170 } ShaderPreview;
171
172 typedef struct IconPreviewSize {
173         struct IconPreviewSize *next, *prev;
174         int sizex, sizey;
175         unsigned int *rect;
176 } IconPreviewSize;
177
178 typedef struct IconPreview {
179         Scene *scene;
180         void *owner;
181         ID *id;
182         ListBase sizes;
183 } IconPreview;
184
185 /* *************************** Preview for buttons *********************** */
186
187 static Main *pr_main = NULL;
188
189 void ED_preview_init_dbase(void)
190 {
191 #ifndef WITH_HEADLESS
192         BlendFileData *bfd;
193         extern int datatoc_preview_blend_size;
194         extern char datatoc_preview_blend[];
195         const int fileflags = G.fileflags;
196         
197         G.fileflags |= G_FILE_NO_UI;
198         bfd = BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, NULL);
199         if (bfd) {
200                 pr_main = bfd->main;
201                 
202                 MEM_freeN(bfd);
203         }
204         G.fileflags = fileflags;
205 #endif
206 }
207
208 void ED_preview_free_dbase(void)
209 {
210         if (pr_main)
211                 free_main(pr_main);
212 }
213
214 static int preview_mat_has_sss(Material *mat, bNodeTree *ntree)
215 {
216         if (mat) {
217                 if (mat->sss_flag & MA_DIFF_SSS)
218                         return 1;
219                 if (mat->nodetree)
220                         if (preview_mat_has_sss(NULL, mat->nodetree))
221                                 return 1;
222         }
223         else if (ntree) {
224                 bNode *node;
225                 for (node = ntree->nodes.first; node; node = node->next) {
226                         if (node->type == NODE_GROUP && node->id) {
227                                 if (preview_mat_has_sss(NULL, (bNodeTree *)node->id))
228                                         return 1;
229                         }
230                         else if (node->id && ELEM(node->type, SH_NODE_MATERIAL, SH_NODE_MATERIAL_EXT)) {
231                                 mat = (Material *)node->id;
232                                 if (mat->sss_flag & MA_DIFF_SSS)
233                                         return 1;
234                         }
235                 }
236         }
237         return 0;
238 }
239
240 static Scene *preview_get_scene(void)
241 {
242         if (pr_main == NULL) return NULL;
243         
244         return pr_main->scene.first;
245 }
246
247
248 /* call this with a pointer to initialize preview scene */
249 /* call this with NULL to restore assigned ID pointers in preview scene */
250 static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPreview *sp)
251 {
252         Scene *sce;
253         Base *base;
254         
255         sce = preview_get_scene();
256         if (sce) {
257                 
258                 /* this flag tells render to not execute depsgraph or ipos etc */
259                 sce->r.scemode |= R_PREVIEWBUTS;
260                 /* set world always back, is used now */
261                 sce->world = pr_main->world.first;
262                 /* now: exposure copy */
263                 if (scene->world) {
264                         sce->world->exp = scene->world->exp;
265                         sce->world->range = scene->world->range;
266                 }
267                 
268                 sce->r.color_mgt_flag = scene->r.color_mgt_flag;
269                 BKE_color_managed_display_settings_copy(&sce->display_settings, &scene->display_settings);
270
271                 BKE_color_managed_view_settings_free(&sce->view_settings);
272                 BKE_color_managed_view_settings_copy(&sce->view_settings, &scene->view_settings);
273                 
274                 /* prevent overhead for small renders and icons (32) */
275                 if (id && sp->sizex < 40) {
276                         sce->r.tilex = sce->r.tiley = 64;
277                 }
278                 else {
279                         sce->r.tilex = sce->r.xsch / 4;
280                         sce->r.tiley = sce->r.ysch / 4;
281                 }
282                 
283                 /* exception: don't apply render part of display transform for texture previews or icons */
284                 if ((id && sp->pr_method == PR_ICON_RENDER) || id_type == ID_TE) {
285                         BKE_scene_disable_color_management(sce);
286                 }
287                 
288                 if ((id && sp->pr_method == PR_ICON_RENDER) && id_type != ID_WO)
289                         sce->r.alphamode = R_ALPHAPREMUL;
290                 else
291                         sce->r.alphamode = R_ADDSKY;
292
293                 sce->r.cfra = scene->r.cfra;
294                 BLI_strncpy(sce->r.engine, scene->r.engine, sizeof(sce->r.engine));
295                 
296                 if (id_type == ID_MA) {
297                         Material *mat = NULL, *origmat = (Material *)id;
298                         
299                         if (origmat) {
300                                 /* work on a copy */
301                                 mat = localize_material(origmat);
302                                 sp->matcopy = mat;
303                                 BLI_addtail(&pr_main->mat, mat);
304                                 
305                                 init_render_material(mat, 0, NULL);     /* call that retrieves mode_l */
306                                 end_render_material(mat);
307                                 
308                                 /* un-useful option */
309                                 if (sp->pr_method == PR_ICON_RENDER)
310                                         mat->shade_flag &= ~MA_OBCOLOR;
311
312                                 /* turn on raytracing if needed */
313                                 if (mat->mode_l & MA_RAYMIRROR)
314                                         sce->r.mode |= R_RAYTRACE;
315                                 if (mat->material_type == MA_TYPE_VOLUME)
316                                         sce->r.mode |= R_RAYTRACE;
317                                 if ((mat->mode_l & MA_RAYTRANSP) && (mat->mode_l & MA_TRANSP))
318                                         sce->r.mode |= R_RAYTRACE;
319                                 if (preview_mat_has_sss(mat, NULL))
320                                         sce->r.mode |= R_SSS;
321                                 
322                                 /* turn off fake shadows if needed */
323                                 /* this only works in a specific case where the preview.blend contains
324                                  * an object starting with 'c' which has a material linked to it (not the obdata)
325                                  * and that material has a fake shadow texture in the active texture slot */
326                                 for (base = sce->base.first; base; base = base->next) {
327                                         if (base->object->id.name[2] == 'c') {
328                                                 Material *shadmat = give_current_material(base->object, base->object->actcol);
329                                                 if (shadmat) {
330                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
331                                                         else shadmat->septex |= 1;
332                                                 }
333                                         }
334                                 }
335                                 
336                                 /* turn off bounce lights for volume, 
337                                  * doesn't make much visual difference and slows it down too */
338                                 if (mat->material_type == MA_TYPE_VOLUME) {
339                                         for (base = sce->base.first; base; base = base->next) {
340                                                 if (base->object->type == OB_LAMP) {
341                                                         /* if doesn't match 'Lamp.002' --> main key light */
342                                                         if (strcmp(base->object->id.name + 2, "Lamp.002") != 0) {
343                                                                 base->object->restrictflag |= OB_RESTRICT_RENDER;
344                                                         }
345                                                 }
346                                         }
347                                 }
348
349                                 
350                                 if (sp->pr_method == PR_ICON_RENDER) {
351                                         if (mat->material_type == MA_TYPE_HALO) {
352                                                 sce->lay = 1 << MA_FLAT;
353                                         }
354                                         else {
355                                                 sce->lay = 1 << MA_SPHERE_A;
356                                         }
357                                 }
358                                 else {
359                                         sce->lay = 1 << mat->pr_type;
360                                         if (mat->nodetree && sp->pr_method == PR_NODE_RENDER) {
361                                                 /* two previews, they get copied by wmJob */
362                                                 ntreeInitPreview(mat->nodetree, sp->sizex, sp->sizey);
363                                                 ntreeInitPreview(origmat->nodetree, sp->sizex, sp->sizey);
364                                         }
365                                 }
366                         }
367                         else {
368                                 sce->r.mode &= ~(R_OSA | R_RAYTRACE | R_SSS);
369                                 
370                         }
371                         
372                         for (base = sce->base.first; base; base = base->next) {
373                                 if (base->object->id.name[2] == 'p') {
374                                         /* copy over object color, in case material uses it */
375                                         copy_v4_v4(base->object->col, sp->col);
376                                         
377                                         if (OB_TYPE_SUPPORT_MATERIAL(base->object->type)) {
378                                                 /* don't use assign_material, it changed mat->id.us, which shows in the UI */
379                                                 Material ***matar = give_matarar(base->object);
380                                                 int actcol = max_ii(base->object->actcol - 1, 0);
381
382                                                 if (matar && actcol < base->object->totcol)
383                                                         (*matar)[actcol] = mat;
384                                         }
385                                         else if (base->object->type == OB_LAMP) {
386                                                 base->object->restrictflag &= ~OB_RESTRICT_RENDER;
387                                         }
388                                 }
389                         }
390                 }
391                 else if (id_type == ID_TE) {
392                         Tex *tex = NULL, *origtex = (Tex *)id;
393                         
394                         if (origtex) {
395                                 tex = localize_texture(origtex);
396                                 sp->texcopy = tex;
397                                 BLI_addtail(&pr_main->tex, tex);
398                         }
399                         sce->lay = 1 << MA_TEXTURE;
400                         
401                         for (base = sce->base.first; base; base = base->next) {
402                                 if (base->object->id.name[2] == 't') {
403                                         Material *mat = give_current_material(base->object, base->object->actcol);
404                                         if (mat && mat->mtex[0]) {
405                                                 mat->mtex[0]->tex = tex;
406                                                 
407                                                 if (tex && sp->slot)
408                                                         mat->mtex[0]->which_output = sp->slot->which_output;
409                                                 
410                                                 /* show alpha in this case */
411                                                 if (tex == NULL || (tex->flag & TEX_PRV_ALPHA)) {
412                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
413                                                         mat->alpha = 0.0f;
414                                                 }
415                                                 else {
416                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
417                                                         mat->alpha = 1.0f;
418                                                 }
419                                         }
420                                 }
421                         }
422
423                         if (tex && tex->nodetree && sp->pr_method == PR_NODE_RENDER) {
424                                 /* two previews, they get copied by wmJob */
425                                 ntreeInitPreview(origtex->nodetree, sp->sizex, sp->sizey);
426                                 ntreeInitPreview(tex->nodetree, sp->sizex, sp->sizey);
427                         }
428                 }
429                 else if (id_type == ID_LA) {
430                         Lamp *la = NULL, *origla = (Lamp *)id;
431
432                         /* work on a copy */
433                         if (origla) {
434                                 la = localize_lamp(origla);
435                                 sp->lampcopy = la;
436                                 BLI_addtail(&pr_main->lamp, la);
437                         }
438                         
439                         if (la && la->type == LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
440                                 sce->lay = 1 << MA_ATMOS;
441                                 sce->world = scene->world;
442                                 sce->camera = (Object *)BLI_findstring(&pr_main->object, "CameraAtmo", offsetof(ID, name) + 2);
443                         }
444                         else {
445                                 sce->lay = 1 << MA_LAMP;
446                                 sce->world = NULL;
447                                 sce->camera = (Object *)BLI_findstring(&pr_main->object, "Camera", offsetof(ID, name) + 2);
448                         }
449                         sce->r.mode &= ~R_SHADOW;
450                         
451                         for (base = sce->base.first; base; base = base->next) {
452                                 if (base->object->id.name[2] == 'p') {
453                                         if (base->object->type == OB_LAMP)
454                                                 base->object->data = la;
455                                 }
456                         }
457
458                         if (la && la->nodetree && sp->pr_method == PR_NODE_RENDER) {
459                                 /* two previews, they get copied by wmJob */
460                                 ntreeInitPreview(origla->nodetree, sp->sizex, sp->sizey);
461                                 ntreeInitPreview(la->nodetree, sp->sizex, sp->sizey);
462                         }
463                 }
464                 else if (id_type == ID_WO) {
465                         World *wrld = NULL, *origwrld = (World *)id;
466
467                         if (origwrld) {
468                                 wrld = localize_world(origwrld);
469                                 sp->worldcopy = wrld;
470                                 BLI_addtail(&pr_main->world, wrld);
471                         }
472
473                         sce->lay = 1 << MA_SKY;
474                         sce->world = wrld;
475
476                         if (wrld && wrld->nodetree && sp->pr_method == PR_NODE_RENDER) {
477                                 /* two previews, they get copied by wmJob */
478                                 ntreeInitPreview(wrld->nodetree, sp->sizex, sp->sizey);
479                                 ntreeInitPreview(origwrld->nodetree, sp->sizex, sp->sizey);
480                         }
481                 }
482                 
483                 return sce;
484         }
485         
486         return NULL;
487 }
488
489 /* new UI convention: draw is in pixel space already. */
490 /* uses ROUNDBOX button in block to get the rect */
491 static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int first, rcti *rect, rcti *newrect)
492 {
493         Render *re;
494         RenderResult rres;
495         char name[32];
496         int do_gamma_correct = FALSE, do_predivide = FALSE;
497         int offx = 0;
498         int newx = BLI_rcti_size_x(rect);
499         int newy = BLI_rcti_size_y(rect);
500
501         if (id && GS(id->name) != ID_TE) {
502                 /* exception: don't color manage texture previews - show the raw values */
503                 if (sce) {
504                         do_gamma_correct = TRUE;
505                         do_predivide = TRUE;
506                 }
507         }
508
509         if (!split || first) sprintf(name, "Preview %p", (void *)sa);
510         else sprintf(name, "SecondPreview %p", (void *)sa);
511
512         if (split) {
513                 if (first) {
514                         offx = 0;
515                         newx = newx / 2;
516                 }
517                 else {
518                         offx = newx / 2;
519                         newx = newx - newx / 2;
520                 }
521         }
522
523         re = RE_GetRender(name);
524         RE_AcquireResultImage(re, &rres);
525
526         if (rres.rectf) {
527                 
528                 if (ABS(rres.rectx - newx) < 2 && ABS(rres.recty - newy) < 2) {
529
530                         newrect->xmax = max_ii(newrect->xmax, rect->xmin + rres.rectx + offx);
531                         newrect->ymax = max_ii(newrect->ymax, rect->ymin + rres.recty);
532
533                         if (rres.rectx && rres.recty) {
534                                 /* temporary conversion to byte for drawing */
535                                 float fx = rect->xmin + offx;
536                                 float fy = rect->ymin;
537                                 int dither = 0;
538                                 unsigned char *rect_byte;
539
540                                 rect_byte = MEM_mallocN(rres.rectx * rres.recty * sizeof(int), "ed_preview_draw_rect");
541
542                                 if (do_gamma_correct) {
543                                         IMB_display_buffer_transform_apply(rect_byte, rres.rectf, rres.rectx, rres.recty, 4,
544                                                                            &sce->view_settings, &sce->display_settings, do_predivide);
545
546                                 }
547                                 else {
548                                         /* OCIO_TODO: currently seems an exception for textures (came fro mlegacish time),
549                                          *            but is it indeed expected behavior, or textures should be
550                                          *            color managed as well?
551                                          */
552                                         IMB_buffer_byte_from_float(rect_byte, rres.rectf,
553                                                                    4, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB, do_predivide,
554                                                                    rres.rectx, rres.recty, rres.rectx, rres.rectx);
555                                 }
556
557                                 glaDrawPixelsSafe(fx, fy, rres.rectx, rres.recty, rres.rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect_byte);
558
559                                 MEM_freeN(rect_byte);
560                         }
561
562                         RE_ReleaseResultImage(re);
563                         return 1;
564                 }
565         }
566
567         RE_ReleaseResultImage(re);
568         return 0;
569 }
570
571 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
572 {
573         if (idp) {
574                 ScrArea *sa = CTX_wm_area(C);
575                 Scene *sce = CTX_data_scene(C);
576                 ID *id = (ID *)idp;
577                 ID *parent = (ID *)parentp;
578                 MTex *slot = (MTex *)slotp;
579                 SpaceButs *sbuts = sa->spacedata.first;
580                 rcti newrect;
581                 int ok;
582                 int newx = BLI_rcti_size_x(rect);
583                 int newy = BLI_rcti_size_y(rect);
584
585                 newrect.xmin = rect->xmin;
586                 newrect.xmax = rect->xmin;
587                 newrect.ymin = rect->ymin;
588                 newrect.ymax = rect->ymin;
589
590                 if (parent) {
591                         ok = ed_preview_draw_rect(sa, sce, id, 1, 1, rect, &newrect);
592                         ok &= ed_preview_draw_rect(sa, sce, parent, 1, 0, rect, &newrect);
593                 }
594                 else
595                         ok = ed_preview_draw_rect(sa, sce, id, 0, 0, rect, &newrect);
596
597                 if (ok)
598                         *rect = newrect;
599
600                 /* check for spacetype... */
601                 if (sbuts->spacetype == SPACE_BUTS && sbuts->preview) {
602                         sbuts->preview = 0;
603                         ok = 0;
604                 }
605         
606                 if (ok == 0) {
607                         ED_preview_shader_job(C, sa, id, parent, slot, newx, newy, PR_BUTS_RENDER);
608                 }
609         }
610 }
611
612 /* **************************** new shader preview system ****************** */
613
614 /* inside thread, called by renderer, sets job update value */
615 static void shader_preview_draw(void *spv, RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect))
616 {
617         ShaderPreview *sp = spv;
618         
619         *(sp->do_update) = TRUE;
620 }
621
622 /* called by renderer, checks job value */
623 static int shader_preview_break(void *spv)
624 {
625         ShaderPreview *sp = spv;
626
627         return *(sp->stop);
628 }
629
630 /* outside thread, called before redraw notifiers, it moves finished preview over */
631 static void shader_preview_updatejob(void *spv)
632 {
633         ShaderPreview *sp = spv;
634         
635         if (sp->id) {
636                 if (sp->pr_method == PR_NODE_RENDER) {
637                         if (GS(sp->id->name) == ID_MA) {
638                                 Material *mat = (Material *)sp->id;
639                                 
640                                 if (sp->matcopy && mat->nodetree && sp->matcopy->nodetree)
641                                         ntreeLocalSync(sp->matcopy->nodetree, mat->nodetree);
642                         }
643                         else if (GS(sp->id->name) == ID_TE) {
644                                 Tex *tex = (Tex *)sp->id;
645                                 
646                                 if (sp->texcopy && tex->nodetree && sp->texcopy->nodetree)
647                                         ntreeLocalSync(sp->texcopy->nodetree, tex->nodetree);
648                         }
649                         else if (GS(sp->id->name) == ID_WO) {
650                                 World *wrld = (World *)sp->id;
651                                 
652                                 if (sp->worldcopy && wrld->nodetree && sp->worldcopy->nodetree)
653                                         ntreeLocalSync(sp->worldcopy->nodetree, wrld->nodetree);
654                         }
655                         else if (GS(sp->id->name) == ID_LA) {
656                                 Lamp *la = (Lamp *)sp->id;
657                                 
658                                 if (sp->lampcopy && la->nodetree && sp->lampcopy->nodetree)
659                                         ntreeLocalSync(sp->lampcopy->nodetree, la->nodetree);
660                         }
661                 }
662         }
663 }
664
665 static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int first)
666 {
667         Render *re;
668         Scene *sce;
669         float oldlens;
670         short idtype = GS(id->name);
671         char name[32];
672         int sizex;
673         
674         /* in case of split preview, use border render */
675         if (split) {
676                 if (first) sizex = sp->sizex / 2;
677                 else sizex = sp->sizex - sp->sizex / 2;
678         }
679         else sizex = sp->sizex;
680         
681         /* we have to set preview variables first */
682         sce = preview_get_scene();
683         if (sce) {
684                 sce->r.xsch = sizex;
685                 sce->r.ysch = sp->sizey;
686                 sce->r.size = 100;
687         }
688         
689         /* get the stuff from the builtin preview dbase */
690         sce = preview_prepare_scene(sp->scene, id, idtype, sp);
691         if (sce == NULL) return;
692         
693         if (!split || first) sprintf(name, "Preview %p", sp->owner);
694         else sprintf(name, "SecondPreview %p", sp->owner);
695         re = RE_GetRender(name);
696         
697         /* full refreshed render from first tile */
698         if (re == NULL)
699                 re = RE_NewRender(name);
700                 
701         /* sce->r gets copied in RE_InitState! */
702         sce->r.scemode &= ~(R_MATNODE_PREVIEW | R_TEXNODE_PREVIEW);
703         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
704
705         if (sp->pr_method == PR_ICON_RENDER) {
706                 sce->r.scemode |= R_NO_IMAGE_LOAD;
707                 sce->r.mode |= R_OSA;
708         }
709         else if (sp->pr_method == PR_NODE_RENDER) {
710                 if (idtype == ID_MA) sce->r.scemode |= R_MATNODE_PREVIEW;
711                 else if (idtype == ID_TE) sce->r.scemode |= R_TEXNODE_PREVIEW;
712                 sce->r.mode &= ~R_OSA;
713         }
714         else {  /* PR_BUTS_RENDER */
715                 sce->r.mode |= R_OSA;
716         }
717
718
719         /* callbacs are cleared on GetRender() */
720         if (ELEM(sp->pr_method, PR_BUTS_RENDER, PR_NODE_RENDER)) {
721                 RE_display_draw_cb(re, sp, shader_preview_draw);
722         }
723         /* set this for all previews, default is react to G.is_break still */
724         RE_test_break_cb(re, sp, shader_preview_break);
725         
726         /* lens adjust */
727         oldlens = ((Camera *)sce->camera->data)->lens;
728         if (sizex > sp->sizey)
729                 ((Camera *)sce->camera->data)->lens *= (float)sp->sizey / (float)sizex;
730
731         /* entire cycle for render engine */
732         RE_PreviewRender(re, pr_main, sce);
733
734         ((Camera *)sce->camera->data)->lens = oldlens;
735
736         /* handle results */
737         if (sp->pr_method == PR_ICON_RENDER) {
738                 // char *rct= (char *)(sp->pr_rect + 32*16 + 16);
739                 
740                 if (sp->pr_rect)
741                         RE_ResultGet32(re, sp->pr_rect);
742         }
743         else {
744                 /* validate owner */
745                 //if (ri->rect == NULL)
746                 //      ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
747                 //RE_ResultGet32(re, ri->rect);
748         }
749
750         /* unassign the pointers, reset vars */
751         preview_prepare_scene(sp->scene, NULL, GS(id->name), sp);
752         
753         /* XXX bad exception, end-exec is not being called in render, because it uses local main */
754 //      if (idtype == ID_TE) {
755 //              Tex *tex= (Tex *)id;
756 //              if (tex->use_nodes && tex->nodetree)
757 //                      ntreeEndExecTree(tex->nodetree);
758 //      }
759
760 }
761
762 /* runs inside thread for material and icons */
763 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
764 {
765         ShaderPreview *sp = customdata;
766
767         sp->stop = stop;
768         sp->do_update = do_update;
769
770         if (sp->parent) {
771                 shader_preview_render(sp, sp->id, 1, 1);
772                 shader_preview_render(sp, sp->parent, 1, 0);
773         }
774         else
775                 shader_preview_render(sp, sp->id, 0, 0);
776
777         *do_update = TRUE;
778 }
779
780 static void shader_preview_free(void *customdata)
781 {
782         ShaderPreview *sp = customdata;
783         
784         if (sp->matcopy) {
785                 struct IDProperty *properties;
786                 
787                 /* node previews */
788                 shader_preview_updatejob(sp);
789                 
790                 /* get rid of copied material */
791                 BLI_remlink(&pr_main->mat, sp->matcopy);
792                 
793                 BKE_material_free_ex(sp->matcopy, FALSE);
794
795                 properties = IDP_GetProperties((ID *)sp->matcopy, FALSE);
796                 if (properties) {
797                         IDP_FreeProperty(properties);
798                         MEM_freeN(properties);
799                 }
800                 MEM_freeN(sp->matcopy);
801         }
802         if (sp->texcopy) {
803                 struct IDProperty *properties;
804                 /* node previews */
805                 shader_preview_updatejob(sp);
806                 
807                 /* get rid of copied texture */
808                 BLI_remlink(&pr_main->tex, sp->texcopy);
809                 BKE_texture_free(sp->texcopy);
810                 
811                 properties = IDP_GetProperties((ID *)sp->texcopy, FALSE);
812                 if (properties) {
813                         IDP_FreeProperty(properties);
814                         MEM_freeN(properties);
815                 }
816                 MEM_freeN(sp->texcopy);
817         }
818         if (sp->worldcopy) {
819                 struct IDProperty *properties;
820                 /* node previews */
821                 shader_preview_updatejob(sp);
822                 
823                 /* get rid of copied world */
824                 BLI_remlink(&pr_main->world, sp->worldcopy);
825                 BKE_world_free_ex(sp->worldcopy, TRUE); /* [#32865] - we need to unlink the texture copies, unlike for materials */
826                 
827                 properties = IDP_GetProperties((ID *)sp->worldcopy, FALSE);
828                 if (properties) {
829                         IDP_FreeProperty(properties);
830                         MEM_freeN(properties);
831                 }
832                 MEM_freeN(sp->worldcopy);
833         }
834         if (sp->lampcopy) {
835                 struct IDProperty *properties;
836                 /* node previews */
837                 shader_preview_updatejob(sp);
838                 
839                 /* get rid of copied lamp */
840                 BLI_remlink(&pr_main->lamp, sp->lampcopy);
841                 BKE_lamp_free(sp->lampcopy);
842                 
843                 properties = IDP_GetProperties((ID *)sp->lampcopy, FALSE);
844                 if (properties) {
845                         IDP_FreeProperty(properties);
846                         MEM_freeN(properties);
847                 }
848                 MEM_freeN(sp->lampcopy);
849         }
850         
851         MEM_freeN(sp);
852 }
853
854 /* ************************* icon preview ********************** */
855
856 static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned int *rect)
857 {
858         struct ImBuf *ima;
859         unsigned int *drect, *srect;
860         float scaledx, scaledy;
861         short ex, ey, dx, dy;
862
863         /* paranoia test */
864         if (ibuf == NULL || (ibuf->rect == NULL && ibuf->rect_float == NULL))
865                 return;
866         
867         /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
868         ima = IMB_dupImBuf(ibuf);
869         
870         if (!ima) 
871                 return;
872         
873         if (ima->x > ima->y) {
874                 scaledx = (float)w;
875                 scaledy =  ( (float)ima->y / (float)ima->x) * (float)w;
876         }
877         else {
878                 scaledx =  ( (float)ima->x / (float)ima->y) * (float)h;
879                 scaledy = (float)h;
880         }
881         
882         ex = (short)scaledx;
883         ey = (short)scaledy;
884         
885         dx = (w - ex) / 2;
886         dy = (h - ey) / 2;
887         
888         IMB_scalefastImBuf(ima, ex, ey);
889         
890         /* if needed, convert to 32 bits */
891         if (ima->rect == NULL)
892                 IMB_rect_from_float(ima);
893
894         srect = ima->rect;
895         drect = rect;
896
897         drect += dy * w + dx;
898         for (; ey > 0; ey--) {
899                 memcpy(drect, srect, ex * sizeof(int));
900                 drect += w;
901                 srect += ima->x;
902         }
903
904         IMB_freeImBuf(ima);
905 }
906
907 static void set_alpha(char *cp, int sizex, int sizey, char alpha) 
908 {
909         int a, size = sizex * sizey;
910
911         for (a = 0; a < size; a++, cp += 4)
912                 cp[3] = alpha;
913 }
914
915 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
916 {
917         ShaderPreview *sp = customdata;
918         ID *id = sp->id;
919         short idtype = GS(id->name);
920
921         if (idtype == ID_IM) {
922                 Image *ima = (Image *)id;
923                 ImBuf *ibuf = NULL;
924                 ImageUser iuser = {NULL};
925
926                 /* ima->ok is zero when Image cannot load */
927                 if (ima == NULL || ima->ok == 0)
928                         return;
929
930                 /* setup dummy image user */
931                 iuser.ok = iuser.framenr = 1;
932                 iuser.scene = sp->scene;
933                 
934                 /* elubie: this needs to be changed: here image is always loaded if not
935                  * already there. Very expensive for large images. Need to find a way to 
936                  * only get existing ibuf */
937                 ibuf = BKE_image_acquire_ibuf(ima, &iuser, NULL);
938                 if (ibuf == NULL || ibuf->rect == NULL)
939                         return;
940                 
941                 icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
942
943                 *do_update = TRUE;
944
945                 BKE_image_release_ibuf(ima, ibuf, NULL);
946         }
947         else if (idtype == ID_BR) {
948                 Brush *br = (Brush *)id;
949
950                 br->icon_imbuf = get_brush_icon(br);
951
952                 memset(sp->pr_rect, 0x888888, sp->sizex * sp->sizey * sizeof(unsigned int));
953
954                 if (!(br->icon_imbuf) || !(br->icon_imbuf->rect))
955                         return;
956
957                 icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
958
959                 *do_update = TRUE;
960         }
961         else {
962                 /* re-use shader job */
963                 shader_preview_startjob(customdata, stop, do_update);
964
965                 /* world is rendered with alpha=0, so it wasn't displayed 
966                  * this could be render option for sky to, for later */
967                 if (idtype == ID_WO) {
968                         set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
969                 }
970                 else if (idtype == ID_MA) {
971                         Material *ma = (Material *)id;
972
973                         if (ma->material_type == MA_TYPE_HALO)
974                                 set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
975                 }
976         }
977 }
978
979 /* use same function for icon & shader, so the job manager
980  * does not run two of them at the same time. */
981
982 static void common_preview_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
983 {
984         ShaderPreview *sp = customdata;
985
986         if (sp->pr_method == PR_ICON_RENDER)
987                 icon_preview_startjob(customdata, stop, do_update);
988         else
989                 shader_preview_startjob(customdata, stop, do_update);
990 }
991
992 /* exported functions */
993
994 static void icon_preview_add_size(IconPreview *ip, unsigned int *rect, int sizex, int sizey)
995 {
996         IconPreviewSize *cur_size = ip->sizes.first, *new_size;
997
998         while (cur_size) {
999                 if (cur_size->sizex == sizex && cur_size->sizey == sizey) {
1000                         /* requested size is already in list, no need to add it again */
1001                         return;
1002                 }
1003
1004                 cur_size = cur_size->next;
1005         }
1006
1007         new_size = MEM_callocN(sizeof(IconPreviewSize), "IconPreviewSize");
1008         new_size->sizex = sizex;
1009         new_size->sizey = sizey;
1010         new_size->rect = rect;
1011
1012         BLI_addtail(&ip->sizes, new_size);
1013 }
1014
1015 static void icon_preview_startjob_all_sizes(void *customdata, short *stop, short *do_update, float *progress)
1016 {
1017         IconPreview *ip = (IconPreview *)customdata;
1018         IconPreviewSize *cur_size = ip->sizes.first;
1019
1020         while (cur_size) {
1021                 ShaderPreview *sp = MEM_callocN(sizeof(ShaderPreview), "Icon ShaderPreview");
1022
1023                 /* construct shader preview from image size and previewcustomdata */
1024                 sp->scene = ip->scene;
1025                 sp->owner = ip->owner;
1026                 sp->sizex = cur_size->sizex;
1027                 sp->sizey = cur_size->sizey;
1028                 sp->pr_method = PR_ICON_RENDER;
1029                 sp->pr_rect = cur_size->rect;
1030                 sp->id = ip->id;
1031
1032                 common_preview_startjob(sp, stop, do_update, progress);
1033                 shader_preview_free(sp);
1034
1035                 cur_size = cur_size->next;
1036         }
1037 }
1038
1039 static void icon_preview_endjob(void *customdata)
1040 {
1041         IconPreview *ip = customdata;
1042
1043         if (ip->id && GS(ip->id->name) == ID_BR)
1044                 WM_main_add_notifier(NC_BRUSH | NA_EDITED, ip->id);
1045 }
1046
1047 static void icon_preview_free(void *customdata)
1048 {
1049         IconPreview *ip = (IconPreview *)customdata;
1050
1051         BLI_freelistN(&ip->sizes);
1052         MEM_freeN(ip);
1053 }
1054
1055 void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *rect, int sizex, int sizey)
1056 {
1057         wmJob *wm_job;
1058         IconPreview *ip, *old_ip;
1059         
1060         /* suspended start means it starts after 1 timer step, see WM_jobs_timer below */
1061         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Icon Preview",
1062                              WM_JOB_EXCL_RENDER | WM_JOB_SUSPEND, WM_JOB_TYPE_RENDER_PREVIEW);
1063
1064         ip = MEM_callocN(sizeof(IconPreview), "icon preview");
1065
1066         /* render all resolutions from suspended job too */
1067         old_ip = WM_jobs_customdata_get(wm_job);
1068         if (old_ip)
1069                 BLI_movelisttolist(&ip->sizes, &old_ip->sizes);
1070
1071         /* customdata for preview thread */
1072         ip->scene = CTX_data_scene(C);
1073         ip->owner = id;
1074         ip->id = id;
1075
1076         icon_preview_add_size(ip, rect, sizex, sizey);
1077
1078         /* setup job */
1079         WM_jobs_customdata_set(wm_job, ip, icon_preview_free);
1080         WM_jobs_timer(wm_job, 0.25, NC_MATERIAL, NC_MATERIAL);
1081         WM_jobs_callbacks(wm_job, icon_preview_startjob_all_sizes, NULL, NULL, icon_preview_endjob);
1082
1083         WM_jobs_start(CTX_wm_manager(C), wm_job);
1084 }
1085
1086 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey, int method)
1087 {
1088         Object *ob = CTX_data_active_object(C);
1089         wmJob *wm_job;
1090         ShaderPreview *sp;
1091
1092         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Shader Preview",
1093                             WM_JOB_EXCL_RENDER, WM_JOB_TYPE_RENDER_PREVIEW);
1094         sp = MEM_callocN(sizeof(ShaderPreview), "shader preview");
1095
1096         /* customdata for preview thread */
1097         sp->scene = CTX_data_scene(C);
1098         sp->owner = owner;
1099         sp->sizex = sizex;
1100         sp->sizey = sizey;
1101         sp->pr_method = method;
1102         sp->id = id;
1103         sp->parent = parent;
1104         sp->slot = slot;
1105         if (ob && ob->totcol) copy_v4_v4(sp->col, ob->col);
1106         else sp->col[0] = sp->col[1] = sp->col[2] = sp->col[3] = 1.0f;
1107         
1108         /* setup job */
1109         WM_jobs_customdata_set(wm_job, sp, shader_preview_free);
1110         WM_jobs_timer(wm_job, 0.1, NC_MATERIAL, NC_MATERIAL);
1111         WM_jobs_callbacks(wm_job, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
1112         
1113         WM_jobs_start(CTX_wm_manager(C), wm_job);
1114 }
1115
1116 void ED_preview_kill_jobs(const struct bContext *C)
1117 {
1118         wmWindowManager *wm = CTX_wm_manager(C);
1119         if (wm)
1120                 WM_jobs_kill(wm, NULL, common_preview_startjob);
1121 }
1122