Merging r50625 through r51896 from trunk into soc-2011-tomato
[blender.git] / source / blender / editors / render / render_preview.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/render/render_preview.c
29  *  \ingroup edrend
30  */
31
32
33 /* global includes */
34
35 #include <stdlib.h>
36 #include <math.h>
37 #include <string.h>
38
39 #ifndef WIN32
40 #include <unistd.h>
41 #else
42 #include <io.h>
43 #endif   
44 #include "MEM_guardedalloc.h"
45
46 #include "BLO_readfile.h" 
47
48 #include "BLI_math.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_threads.h"
51 #include "BLI_utildefines.h"
52
53 #include "DNA_world_types.h"
54 #include "DNA_camera_types.h"
55 #include "DNA_material_types.h"
56 #include "DNA_node_types.h"
57 #include "DNA_object_types.h"
58 #include "DNA_lamp_types.h"
59 #include "DNA_space_types.h"
60 #include "DNA_view3d_types.h"
61 #include "DNA_scene_types.h"
62 #include "DNA_brush_types.h"
63 #include "DNA_screen_types.h"
64
65 #include "BKE_brush.h"
66 #include "BKE_context.h"
67 #include "BKE_colortools.h"
68 #include "BKE_depsgraph.h"
69 #include "BKE_global.h"
70 #include "BKE_idprop.h"
71 #include "BKE_image.h"
72 #include "BKE_icons.h"
73 #include "BKE_lamp.h"
74 #include "BKE_library.h"
75 #include "BKE_main.h"
76 #include "BKE_material.h"
77 #include "BKE_node.h"
78 #include "BKE_object.h"
79 #include "BKE_scene.h"
80 #include "BKE_texture.h"
81 #include "BKE_world.h"
82
83 #include "IMB_imbuf.h"
84 #include "IMB_imbuf_types.h"
85 #include "IMB_colormanagement.h"
86
87 #include "BIF_gl.h"
88 #include "BIF_glutil.h"
89
90 #include "PIL_time.h"
91
92 #include "RE_pipeline.h"
93
94
95 #include "WM_api.h"
96 #include "WM_types.h"
97
98 #include "ED_render.h"
99 #include "ED_view3d.h"
100
101 #include "UI_interface.h"
102
103 #include "render_intern.h"
104
105 ImBuf *get_brush_icon(Brush *brush)
106 {
107         static const int flags = IB_rect | IB_multilayer | IB_metadata;
108
109         char path[FILE_MAX];
110         char *folder;
111
112         if (!(brush->icon_imbuf)) {
113                 if (brush->flag & BRUSH_CUSTOM_ICON) {
114
115                         if (brush->icon_filepath[0]) {
116                                 // first use the path directly to try and load the file
117
118                                 BLI_strncpy(path, brush->icon_filepath, sizeof(brush->icon_filepath));
119                                 BLI_path_abs(path, G.main->name);
120
121                                 /* use default colorspaces for brushes */
122                                 brush->icon_imbuf = IMB_loadiffname(path, flags, NULL);
123
124                                 // otherwise lets try to find it in other directories
125                                 if (!(brush->icon_imbuf)) {
126                                         folder = BLI_get_folder(BLENDER_DATAFILES, "brushicons");
127
128                                         BLI_make_file_string(G.main->name, path, folder, brush->icon_filepath);
129
130                                         if (path[0]) {
131                                                 /* use fefault color spaces */
132                                                 brush->icon_imbuf = IMB_loadiffname(path, flags, NULL);
133                                         }
134                                 }
135
136                                 if (brush->icon_imbuf)
137                                         BKE_icon_changed(BKE_icon_getid(&brush->id));
138                         }
139                 }
140         }
141
142         if (!(brush->icon_imbuf))
143                 brush->id.icon_id = 0;
144
145         return brush->icon_imbuf;
146 }
147
148 typedef struct ShaderPreview {
149         /* from wmJob */
150         void *owner;
151         short *stop, *do_update;
152         
153         Scene *scene;
154         ID *id;
155         ID *parent;
156         MTex *slot;
157         
158         /* datablocks with nodes need full copy during preview render, glsl uses it too */
159         Material *matcopy;
160         Tex *texcopy;
161         Lamp *lampcopy;
162         World *worldcopy;
163         
164         float col[4];       /* active object color */
165         
166         int sizex, sizey;
167         unsigned int *pr_rect;
168         int pr_method;
169         
170 } ShaderPreview;
171
172 typedef struct IconPreviewSize {
173         struct IconPreviewSize *next, *prev;
174         int sizex, sizey;
175         unsigned int *rect;
176 } IconPreviewSize;
177
178 typedef struct IconPreview {
179         Scene *scene;
180         void *owner;
181         ID *id;
182         ListBase sizes;
183 } IconPreview;
184
185 /* *************************** Preview for buttons *********************** */
186
187 static Main *pr_main = NULL;
188
189 void ED_preview_init_dbase(void)
190 {
191 #ifndef WITH_HEADLESS
192         BlendFileData *bfd;
193         extern int datatoc_preview_blend_size;
194         extern char datatoc_preview_blend[];
195         const int fileflags = G.fileflags;
196         
197         G.fileflags |= G_FILE_NO_UI;
198         bfd = BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, NULL);
199         if (bfd) {
200                 pr_main = bfd->main;
201                 
202                 MEM_freeN(bfd);
203         }
204         G.fileflags = fileflags;
205 #endif
206 }
207
208 void ED_preview_free_dbase(void)
209 {
210         if (pr_main)
211                 free_main(pr_main);
212 }
213
214 static int preview_mat_has_sss(Material *mat, bNodeTree *ntree)
215 {
216         if (mat) {
217                 if (mat->sss_flag & MA_DIFF_SSS)
218                         return 1;
219                 if (mat->nodetree)
220                         if (preview_mat_has_sss(NULL, mat->nodetree))
221                                 return 1;
222         }
223         else if (ntree) {
224                 bNode *node;
225                 for (node = ntree->nodes.first; node; node = node->next) {
226                         if (node->type == NODE_GROUP && node->id) {
227                                 if (preview_mat_has_sss(NULL, (bNodeTree *)node->id))
228                                         return 1;
229                         }
230                         else if (node->id && ELEM(node->type, SH_NODE_MATERIAL, SH_NODE_MATERIAL_EXT)) {
231                                 mat = (Material *)node->id;
232                                 if (mat->sss_flag & MA_DIFF_SSS)
233                                         return 1;
234                         }
235                 }
236         }
237         return 0;
238 }
239
240 /* call this with a pointer to initialize preview scene */
241 /* call this with NULL to restore assigned ID pointers in preview scene */
242 static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPreview *sp)
243 {
244         Scene *sce;
245         Base *base;
246         
247         if (pr_main == NULL) return NULL;
248         
249         sce = pr_main->scene.first;
250         if (sce) {
251                 
252                 /* this flag tells render to not execute depsgraph or ipos etc */
253                 sce->r.scemode |= R_PREVIEWBUTS;
254                 /* set world always back, is used now */
255                 sce->world = pr_main->world.first;
256                 /* now: exposure copy */
257                 if (scene->world) {
258                         sce->world->exp = scene->world->exp;
259                         sce->world->range = scene->world->range;
260                 }
261                 
262                 sce->r.color_mgt_flag = scene->r.color_mgt_flag;
263                 BKE_color_managed_display_settings_copy(&sce->display_settings, &scene->display_settings);
264
265                 BKE_color_managed_view_settings_free(&sce->view_settings);
266                 BKE_color_managed_view_settings_copy(&sce->view_settings, &scene->view_settings);
267                 
268                 /* prevent overhead for small renders and icons (32) */
269                 if (id && sp->sizex < 40) {
270                         sce->r.tilex = sce->r.tiley = 64;
271                 }
272                 else {
273                         sce->r.tilex = sce->r.xsch / 4;
274                         sce->r.tiley = sce->r.ysch / 4;
275                 }
276                 
277                 /* exception: don't apply render part of display transform for texture previews or icons */
278                 if ((id && sp->pr_method == PR_ICON_RENDER) || id_type == ID_TE) {
279                         BKE_scene_disable_color_management(sce);
280                 }
281                 
282                 if ((id && sp->pr_method == PR_ICON_RENDER) && id_type != ID_WO)
283                         sce->r.alphamode = R_ALPHAPREMUL;
284                 else
285                         sce->r.alphamode = R_ADDSKY;
286
287                 sce->r.cfra = scene->r.cfra;
288                 BLI_strncpy(sce->r.engine, scene->r.engine, sizeof(sce->r.engine));
289                 
290                 if (id_type == ID_MA) {
291                         Material *mat = NULL, *origmat = (Material *)id;
292                         
293                         if (origmat) {
294                                 /* work on a copy */
295                                 mat = localize_material(origmat);
296                                 sp->matcopy = mat;
297                                 BLI_addtail(&pr_main->mat, mat);
298                                 
299                                 init_render_material(mat, 0, NULL);     /* call that retrieves mode_l */
300                                 end_render_material(mat);
301                                 
302                                 /* un-useful option */
303                                 if (sp->pr_method == PR_ICON_RENDER)
304                                         mat->shade_flag &= ~MA_OBCOLOR;
305
306                                 /* turn on raytracing if needed */
307                                 if (mat->mode_l & MA_RAYMIRROR)
308                                         sce->r.mode |= R_RAYTRACE;
309                                 if (mat->material_type == MA_TYPE_VOLUME)
310                                         sce->r.mode |= R_RAYTRACE;
311                                 if ((mat->mode_l & MA_RAYTRANSP) && (mat->mode_l & MA_TRANSP))
312                                         sce->r.mode |= R_RAYTRACE;
313                                 if (preview_mat_has_sss(mat, NULL))
314                                         sce->r.mode |= R_SSS;
315                                 
316                                 /* turn off fake shadows if needed */
317                                 /* this only works in a specific case where the preview.blend contains
318                                  * an object starting with 'c' which has a material linked to it (not the obdata)
319                                  * and that material has a fake shadow texture in the active texture slot */
320                                 for (base = sce->base.first; base; base = base->next) {
321                                         if (base->object->id.name[2] == 'c') {
322                                                 Material *shadmat = give_current_material(base->object, base->object->actcol);
323                                                 if (shadmat) {
324                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
325                                                         else shadmat->septex |= 1;
326                                                 }
327                                         }
328                                 }
329                                 
330                                 /* turn off bounce lights for volume, 
331                                  * doesn't make much visual difference and slows it down too */
332                                 if (mat->material_type == MA_TYPE_VOLUME) {
333                                         for (base = sce->base.first; base; base = base->next) {
334                                                 if (base->object->type == OB_LAMP) {
335                                                         /* if doesn't match 'Lamp.002' --> main key light */
336                                                         if (strcmp(base->object->id.name + 2, "Lamp.002") != 0) {
337                                                                 base->object->restrictflag |= OB_RESTRICT_RENDER;
338                                                         }
339                                                 }
340                                         }
341                                 }
342
343                                 
344                                 if (sp->pr_method == PR_ICON_RENDER) {
345                                         if (mat->material_type == MA_TYPE_HALO) {
346                                                 sce->lay = 1 << MA_FLAT;
347                                         }
348                                         else {
349                                                 sce->lay = 1 << MA_SPHERE_A;
350                                         }
351                                 }
352                                 else {
353                                         sce->lay = 1 << mat->pr_type;
354                                         if (mat->nodetree && sp->pr_method == PR_NODE_RENDER) {
355                                                 /* two previews, they get copied by wmJob */
356                                                 ntreeInitPreview(mat->nodetree, sp->sizex, sp->sizey);
357                                                 ntreeInitPreview(origmat->nodetree, sp->sizex, sp->sizey);
358                                         }
359                                 }
360                         }
361                         else {
362                                 sce->r.mode &= ~(R_OSA | R_RAYTRACE | R_SSS);
363                                 
364                         }
365                         
366                         for (base = sce->base.first; base; base = base->next) {
367                                 if (base->object->id.name[2] == 'p') {
368                                         /* copy over object color, in case material uses it */
369                                         copy_v4_v4(base->object->col, sp->col);
370                                         
371                                         if (OB_TYPE_SUPPORT_MATERIAL(base->object->type)) {
372                                                 /* don't use assign_material, it changed mat->id.us, which shows in the UI */
373                                                 Material ***matar = give_matarar(base->object);
374                                                 int actcol = max_ii(base->object->actcol - 1, 0);
375
376                                                 if (matar && actcol < base->object->totcol)
377                                                         (*matar)[actcol] = mat;
378                                         }
379                                         else if (base->object->type == OB_LAMP) {
380                                                 base->object->restrictflag &= ~OB_RESTRICT_RENDER;
381                                         }
382                                 }
383                         }
384                 }
385                 else if (id_type == ID_TE) {
386                         Tex *tex = NULL, *origtex = (Tex *)id;
387                         
388                         if (origtex) {
389                                 tex = localize_texture(origtex);
390                                 sp->texcopy = tex;
391                                 BLI_addtail(&pr_main->tex, tex);
392                         }
393                         sce->lay = 1 << MA_TEXTURE;
394                         
395                         for (base = sce->base.first; base; base = base->next) {
396                                 if (base->object->id.name[2] == 't') {
397                                         Material *mat = give_current_material(base->object, base->object->actcol);
398                                         if (mat && mat->mtex[0]) {
399                                                 mat->mtex[0]->tex = tex;
400                                                 
401                                                 if (tex && sp->slot)
402                                                         mat->mtex[0]->which_output = sp->slot->which_output;
403                                                 
404                                                 /* show alpha in this case */
405                                                 if (tex == NULL || (tex->flag & TEX_PRV_ALPHA)) {
406                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
407                                                         mat->alpha = 0.0f;
408                                                 }
409                                                 else {
410                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
411                                                         mat->alpha = 1.0f;
412                                                 }
413                                         }
414                                 }
415                         }
416
417                         if (tex && tex->nodetree && sp->pr_method == PR_NODE_RENDER) {
418                                 /* two previews, they get copied by wmJob */
419                                 ntreeInitPreview(origtex->nodetree, sp->sizex, sp->sizey);
420                                 ntreeInitPreview(tex->nodetree, sp->sizex, sp->sizey);
421                         }
422                 }
423                 else if (id_type == ID_LA) {
424                         Lamp *la = NULL, *origla = (Lamp *)id;
425
426                         /* work on a copy */
427                         if (origla) {
428                                 la = localize_lamp(origla);
429                                 sp->lampcopy = la;
430                                 BLI_addtail(&pr_main->lamp, la);
431                         }
432                         
433                         if (la && la->type == LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
434                                 sce->lay = 1 << MA_ATMOS;
435                                 sce->world = scene->world;
436                                 sce->camera = (Object *)BLI_findstring(&pr_main->object, "CameraAtmo", offsetof(ID, name) + 2);
437                         }
438                         else {
439                                 sce->lay = 1 << MA_LAMP;
440                                 sce->world = NULL;
441                                 sce->camera = (Object *)BLI_findstring(&pr_main->object, "Camera", offsetof(ID, name) + 2);
442                         }
443                         sce->r.mode &= ~R_SHADOW;
444                         
445                         for (base = sce->base.first; base; base = base->next) {
446                                 if (base->object->id.name[2] == 'p') {
447                                         if (base->object->type == OB_LAMP)
448                                                 base->object->data = la;
449                                 }
450                         }
451
452                         if (la && la->nodetree && sp->pr_method == PR_NODE_RENDER) {
453                                 /* two previews, they get copied by wmJob */
454                                 ntreeInitPreview(origla->nodetree, sp->sizex, sp->sizey);
455                                 ntreeInitPreview(la->nodetree, sp->sizex, sp->sizey);
456                         }
457                 }
458                 else if (id_type == ID_WO) {
459                         World *wrld = NULL, *origwrld = (World *)id;
460
461                         if (origwrld) {
462                                 wrld = localize_world(origwrld);
463                                 sp->worldcopy = wrld;
464                                 BLI_addtail(&pr_main->world, wrld);
465                         }
466
467                         sce->lay = 1 << MA_SKY;
468                         sce->world = wrld;
469
470                         if (wrld && wrld->nodetree && sp->pr_method == PR_NODE_RENDER) {
471                                 /* two previews, they get copied by wmJob */
472                                 ntreeInitPreview(wrld->nodetree, sp->sizex, sp->sizey);
473                                 ntreeInitPreview(origwrld->nodetree, sp->sizex, sp->sizey);
474                         }
475                 }
476                 
477                 return sce;
478         }
479         
480         return NULL;
481 }
482
483 /* new UI convention: draw is in pixel space already. */
484 /* uses ROUNDBOX button in block to get the rect */
485 static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int first, rcti *rect, rcti *newrect)
486 {
487         Render *re;
488         RenderResult rres;
489         char name[32];
490         int do_gamma_correct = FALSE, do_predivide = FALSE;
491         int offx = 0;
492         int newx = BLI_rcti_size_x(rect);
493         int newy = BLI_rcti_size_y(rect);
494
495         if (id && GS(id->name) != ID_TE) {
496                 /* exception: don't color manage texture previews - show the raw values */
497                 if (sce) {
498                         do_gamma_correct = TRUE;
499                         do_predivide = sce->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE;
500                 }
501         }
502
503         if (!split || first) sprintf(name, "Preview %p", (void *)sa);
504         else sprintf(name, "SecondPreview %p", (void *)sa);
505
506         if (split) {
507                 if (first) {
508                         offx = 0;
509                         newx = newx / 2;
510                 }
511                 else {
512                         offx = newx / 2;
513                         newx = newx - newx / 2;
514                 }
515         }
516
517         re = RE_GetRender(name);
518         RE_AcquireResultImage(re, &rres);
519
520         if (rres.rectf) {
521                 
522                 if (ABS(rres.rectx - newx) < 2 && ABS(rres.recty - newy) < 2) {
523
524                         newrect->xmax = max_ii(newrect->xmax, rect->xmin + rres.rectx + offx);
525                         newrect->ymax = max_ii(newrect->ymax, rect->ymin + rres.recty);
526
527                         if (rres.rectx && rres.recty) {
528                                 /* temporary conversion to byte for drawing */
529                                 float fx = rect->xmin + offx;
530                                 float fy = rect->ymin;
531                                 int dither = 0;
532                                 unsigned char *rect_byte;
533
534                                 rect_byte = MEM_mallocN(rres.rectx * rres.recty * sizeof(int), "ed_preview_draw_rect");
535
536                                 if (do_gamma_correct) {
537                                         IMB_display_buffer_transform_apply(rect_byte, rres.rectf, rres.rectx, rres.recty, 4,
538                                                                            &sce->view_settings, &sce->display_settings, do_predivide);
539
540                                 }
541                                 else {
542                                         /* OCIO_TODO: currently seems an exception for textures (came fro mlegacish time),
543                                          *            but is it indeed expected behavior, or textures should be
544                                          *            color managed as well?
545                                          */
546                                         IMB_buffer_byte_from_float(rect_byte, rres.rectf,
547                                                                    4, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB, do_predivide,
548                                                                    rres.rectx, rres.recty, rres.rectx, rres.rectx);
549                                 }
550
551                                 glaDrawPixelsSafe(fx, fy, rres.rectx, rres.recty, rres.rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect_byte);
552
553                                 MEM_freeN(rect_byte);
554                         }
555
556                         RE_ReleaseResultImage(re);
557                         return 1;
558                 }
559         }
560
561         RE_ReleaseResultImage(re);
562         return 0;
563 }
564
565 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
566 {
567         if (idp) {
568                 ScrArea *sa = CTX_wm_area(C);
569                 Scene *sce = CTX_data_scene(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, sce, id, 1, 1, rect, &newrect);
586                         ok &= ed_preview_draw_rect(sa, sce, parent, 1, 0, rect, &newrect);
587                 }
588                 else
589                         ok = ed_preview_draw_rect(sa, sce, id, 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         
668         /* get the stuff from the builtin preview dbase */
669         sce = preview_prepare_scene(sp->scene, id, idtype, sp); // XXX sizex
670         if (sce == NULL) return;
671         
672         if (!split || first) sprintf(name, "Preview %p", sp->owner);
673         else sprintf(name, "SecondPreview %p", sp->owner);
674         re = RE_GetRender(name);
675         
676         /* full refreshed render from first tile */
677         if (re == NULL)
678                 re = RE_NewRender(name);
679                 
680         /* sce->r gets copied in RE_InitState! */
681         sce->r.scemode &= ~(R_MATNODE_PREVIEW | R_TEXNODE_PREVIEW);
682         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
683
684         if (sp->pr_method == PR_ICON_RENDER) {
685                 sce->r.scemode |= R_NO_IMAGE_LOAD;
686                 sce->r.mode |= R_OSA;
687         }
688         else if (sp->pr_method == PR_NODE_RENDER) {
689                 if (idtype == ID_MA) sce->r.scemode |= R_MATNODE_PREVIEW;
690                 else if (idtype == ID_TE) sce->r.scemode |= R_TEXNODE_PREVIEW;
691                 sce->r.mode &= ~R_OSA;
692         }
693         else {  /* PR_BUTS_RENDER */
694                 sce->r.mode |= R_OSA;
695         }
696
697         /* in case of split preview, use border render */
698         if (split) {
699                 if (first) sizex = sp->sizex / 2;
700                 else sizex = sp->sizex - sp->sizex / 2;
701         }
702         else sizex = sp->sizex;
703
704         /* allocates or re-uses render result */
705         sce->r.xsch = sizex;
706         sce->r.ysch = sp->sizey;
707         sce->r.size = 100;
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         
774         if (sp->matcopy) {
775                 struct IDProperty *properties;
776                 
777                 /* node previews */
778                 shader_preview_updatejob(sp);
779                 
780                 /* get rid of copied material */
781                 BLI_remlink(&pr_main->mat, sp->matcopy);
782                 
783                 BKE_material_free_ex(sp->matcopy, FALSE);
784
785                 properties = IDP_GetProperties((ID *)sp->matcopy, FALSE);
786                 if (properties) {
787                         IDP_FreeProperty(properties);
788                         MEM_freeN(properties);
789                 }
790                 MEM_freeN(sp->matcopy);
791         }
792         if (sp->texcopy) {
793                 struct IDProperty *properties;
794                 /* node previews */
795                 shader_preview_updatejob(sp);
796                 
797                 /* get rid of copied texture */
798                 BLI_remlink(&pr_main->tex, sp->texcopy);
799                 BKE_texture_free(sp->texcopy);
800                 
801                 properties = IDP_GetProperties((ID *)sp->texcopy, FALSE);
802                 if (properties) {
803                         IDP_FreeProperty(properties);
804                         MEM_freeN(properties);
805                 }
806                 MEM_freeN(sp->texcopy);
807         }
808         if (sp->worldcopy) {
809                 struct IDProperty *properties;
810                 /* node previews */
811                 shader_preview_updatejob(sp);
812                 
813                 /* get rid of copied world */
814                 BLI_remlink(&pr_main->world, sp->worldcopy);
815                 BKE_world_free_ex(sp->worldcopy, TRUE); /* [#32865] - we need to unlink the texture copies, unlike for materials */
816                 
817                 properties = IDP_GetProperties((ID *)sp->worldcopy, FALSE);
818                 if (properties) {
819                         IDP_FreeProperty(properties);
820                         MEM_freeN(properties);
821                 }
822                 MEM_freeN(sp->worldcopy);
823         }
824         if (sp->lampcopy) {
825                 struct IDProperty *properties;
826                 /* node previews */
827                 shader_preview_updatejob(sp);
828                 
829                 /* get rid of copied lamp */
830                 BLI_remlink(&pr_main->lamp, sp->lampcopy);
831                 BKE_lamp_free(sp->lampcopy);
832                 
833                 properties = IDP_GetProperties((ID *)sp->lampcopy, FALSE);
834                 if (properties) {
835                         IDP_FreeProperty(properties);
836                         MEM_freeN(properties);
837                 }
838                 MEM_freeN(sp->lampcopy);
839         }
840         
841         MEM_freeN(sp);
842 }
843
844 /* ************************* icon preview ********************** */
845
846 static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned int *rect)
847 {
848         struct ImBuf *ima;
849         unsigned int *drect, *srect;
850         float scaledx, scaledy;
851         short ex, ey, dx, dy;
852
853         /* paranoia test */
854         if (ibuf == NULL || (ibuf->rect == NULL && ibuf->rect_float == NULL))
855                 return;
856         
857         /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
858         ima = IMB_dupImBuf(ibuf);
859         
860         if (!ima) 
861                 return;
862         
863         if (ima->x > ima->y) {
864                 scaledx = (float)w;
865                 scaledy =  ( (float)ima->y / (float)ima->x) * (float)w;
866         }
867         else {
868                 scaledx =  ( (float)ima->x / (float)ima->y) * (float)h;
869                 scaledy = (float)h;
870         }
871         
872         ex = (short)scaledx;
873         ey = (short)scaledy;
874         
875         dx = (w - ex) / 2;
876         dy = (h - ey) / 2;
877         
878         IMB_scalefastImBuf(ima, ex, ey);
879         
880         /* if needed, convert to 32 bits */
881         if (ima->rect == NULL)
882                 IMB_rect_from_float(ima);
883
884         srect = ima->rect;
885         drect = rect;
886
887         drect += dy * w + dx;
888         for (; ey > 0; ey--) {
889                 memcpy(drect, srect, ex * sizeof(int));
890                 drect += w;
891                 srect += ima->x;
892         }
893
894         IMB_freeImBuf(ima);
895 }
896
897 static void set_alpha(char *cp, int sizex, int sizey, char alpha) 
898 {
899         int a, size = sizex * sizey;
900
901         for (a = 0; a < size; a++, cp += 4)
902                 cp[3] = alpha;
903 }
904
905 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
906 {
907         ShaderPreview *sp = customdata;
908         ID *id = sp->id;
909         short idtype = GS(id->name);
910
911         if (idtype == ID_IM) {
912                 Image *ima = (Image *)id;
913                 ImBuf *ibuf = NULL;
914                 ImageUser iuser = {NULL};
915
916                 /* ima->ok is zero when Image cannot load */
917                 if (ima == NULL || ima->ok == 0)
918                         return;
919
920                 /* setup dummy image user */
921                 iuser.ok = iuser.framenr = 1;
922                 iuser.scene = sp->scene;
923                 
924                 /* elubie: this needs to be changed: here image is always loaded if not
925                  * already there. Very expensive for large images. Need to find a way to 
926                  * only get existing ibuf */
927                 ibuf = BKE_image_get_ibuf(ima, &iuser);
928                 if (ibuf == NULL || ibuf->rect == NULL)
929                         return;
930                 
931                 icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
932
933                 *do_update = TRUE;
934         }
935         else if (idtype == ID_BR) {
936                 Brush *br = (Brush *)id;
937
938                 br->icon_imbuf = get_brush_icon(br);
939
940                 memset(sp->pr_rect, 0x888888, sp->sizex * sp->sizey * sizeof(unsigned int));
941
942                 if (!(br->icon_imbuf) || !(br->icon_imbuf->rect))
943                         return;
944
945                 icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
946
947                 *do_update = TRUE;
948         }
949         else {
950                 /* re-use shader job */
951                 shader_preview_startjob(customdata, stop, do_update);
952
953                 /* world is rendered with alpha=0, so it wasn't displayed 
954                  * this could be render option for sky to, for later */
955                 if (idtype == ID_WO) {
956                         set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
957                 }
958                 else if (idtype == ID_MA) {
959                         Material *ma = (Material *)id;
960
961                         if (ma->material_type == MA_TYPE_HALO)
962                                 set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
963                 }
964         }
965 }
966
967 /* use same function for icon & shader, so the job manager
968  * does not run two of them at the same time. */
969
970 static void common_preview_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
971 {
972         ShaderPreview *sp = customdata;
973
974         if (sp->pr_method == PR_ICON_RENDER)
975                 icon_preview_startjob(customdata, stop, do_update);
976         else
977                 shader_preview_startjob(customdata, stop, do_update);
978 }
979
980 /* exported functions */
981
982 static void icon_preview_add_size(IconPreview *ip, unsigned int *rect, int sizex, int sizey)
983 {
984         IconPreviewSize *cur_size = ip->sizes.first, *new_size;
985
986         while (cur_size) {
987                 if (cur_size->sizex == sizex && cur_size->sizey == sizey) {
988                         /* requested size is already in list, no need to add it again */
989                         return;
990                 }
991
992                 cur_size = cur_size->next;
993         }
994
995         new_size = MEM_callocN(sizeof(IconPreviewSize), "IconPreviewSize");
996         new_size->sizex = sizex;
997         new_size->sizey = sizey;
998         new_size->rect = rect;
999
1000         BLI_addtail(&ip->sizes, new_size);
1001 }
1002
1003 static void icon_preview_startjob_all_sizes(void *customdata, short *stop, short *do_update, float *progress)
1004 {
1005         IconPreview *ip = (IconPreview *)customdata;
1006         IconPreviewSize *cur_size = ip->sizes.first;
1007
1008         while (cur_size) {
1009                 ShaderPreview *sp = MEM_callocN(sizeof(ShaderPreview), "Icon ShaderPreview");
1010
1011                 /* construct shader preview from image size and previewcustomdata */
1012                 sp->scene = ip->scene;
1013                 sp->owner = ip->owner;
1014                 sp->sizex = cur_size->sizex;
1015                 sp->sizey = cur_size->sizey;
1016                 sp->pr_method = PR_ICON_RENDER;
1017                 sp->pr_rect = cur_size->rect;
1018                 sp->id = ip->id;
1019
1020                 common_preview_startjob(sp, stop, do_update, progress);
1021                 shader_preview_free(sp);
1022
1023                 cur_size = cur_size->next;
1024         }
1025 }
1026
1027 static void icon_preview_endjob(void *customdata)
1028 {
1029         IconPreview *ip = customdata;
1030
1031         if (ip->id && GS(ip->id->name) == ID_BR)
1032                 WM_main_add_notifier(NC_BRUSH | NA_EDITED, ip->id);
1033 }
1034
1035 static void icon_preview_free(void *customdata)
1036 {
1037         IconPreview *ip = (IconPreview *)customdata;
1038
1039         BLI_freelistN(&ip->sizes);
1040         MEM_freeN(ip);
1041 }
1042
1043 void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *rect, int sizex, int sizey)
1044 {
1045         wmJob *wm_job;
1046         IconPreview *ip, *old_ip;
1047         
1048         /* suspended start means it starts after 1 timer step, see WM_jobs_timer below */
1049         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Icon Preview",
1050                              WM_JOB_EXCL_RENDER | WM_JOB_SUSPEND, WM_JOB_TYPE_RENDER_PREVIEW);
1051
1052         ip = MEM_callocN(sizeof(IconPreview), "icon preview");
1053
1054         /* render all resolutions from suspended job too */
1055         old_ip = WM_jobs_customdata_get(wm_job);
1056         if (old_ip)
1057                 BLI_movelisttolist(&ip->sizes, &old_ip->sizes);
1058
1059         /* customdata for preview thread */
1060         ip->scene = CTX_data_scene(C);
1061         ip->owner = id;
1062         ip->id = id;
1063
1064         icon_preview_add_size(ip, rect, sizex, sizey);
1065
1066         /* setup job */
1067         WM_jobs_customdata_set(wm_job, ip, icon_preview_free);
1068         WM_jobs_timer(wm_job, 0.25, NC_MATERIAL, NC_MATERIAL);
1069         WM_jobs_callbacks(wm_job, icon_preview_startjob_all_sizes, NULL, NULL, icon_preview_endjob);
1070
1071         WM_jobs_start(CTX_wm_manager(C), wm_job);
1072 }
1073
1074 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey, int method)
1075 {
1076         Object *ob = CTX_data_active_object(C);
1077         wmJob *wm_job;
1078         ShaderPreview *sp;
1079
1080         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Shader Preview",
1081                             WM_JOB_EXCL_RENDER, WM_JOB_TYPE_RENDER_PREVIEW);
1082         sp = MEM_callocN(sizeof(ShaderPreview), "shader preview");
1083
1084         /* customdata for preview thread */
1085         sp->scene = CTX_data_scene(C);
1086         sp->owner = owner;
1087         sp->sizex = sizex;
1088         sp->sizey = sizey;
1089         sp->pr_method = method;
1090         sp->id = id;
1091         sp->parent = parent;
1092         sp->slot = slot;
1093         if (ob && ob->totcol) copy_v4_v4(sp->col, ob->col);
1094         else sp->col[0] = sp->col[1] = sp->col[2] = sp->col[3] = 1.0f;
1095         
1096         /* setup job */
1097         WM_jobs_customdata_set(wm_job, sp, shader_preview_free);
1098         WM_jobs_timer(wm_job, 0.1, NC_MATERIAL, NC_MATERIAL);
1099         WM_jobs_callbacks(wm_job, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
1100         
1101         WM_jobs_start(CTX_wm_manager(C), wm_job);
1102 }
1103
1104 void ED_preview_kill_jobs(const struct bContext *C)
1105 {
1106         wmWindowManager *wm = CTX_wm_manager(C);
1107         if (wm)
1108                 WM_jobs_kill(wm, NULL, common_preview_startjob);
1109 }
1110