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