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