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