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