code cleanup: favor braces when blocks have mixed brace use.
[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 {
675                 sizex = sp->sizex;
676         }
677
678         /* we have to set preview variables first */
679         sce = preview_get_scene(pr_main);
680         if (sce) {
681                 sce->r.xsch = sizex;
682                 sce->r.ysch = sp->sizey;
683                 sce->r.size = 100;
684         }
685         
686         /* get the stuff from the builtin preview dbase */
687         sce = preview_prepare_scene(sp->scene, id, idtype, sp);
688         if (sce == NULL) return;
689         
690         if (!split || first) sprintf(name, "Preview %p", sp->owner);
691         else sprintf(name, "SecondPreview %p", sp->owner);
692         re = RE_GetRender(name);
693         
694         /* full refreshed render from first tile */
695         if (re == NULL)
696                 re = RE_NewRender(name);
697                 
698         /* sce->r gets copied in RE_InitState! */
699         sce->r.scemode &= ~(R_MATNODE_PREVIEW | R_TEXNODE_PREVIEW);
700         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
701
702         if (sp->pr_method == PR_ICON_RENDER) {
703                 sce->r.scemode |= R_NO_IMAGE_LOAD;
704                 sce->r.mode |= R_OSA;
705         }
706         else if (sp->pr_method == PR_NODE_RENDER) {
707                 if (idtype == ID_MA) sce->r.scemode |= R_MATNODE_PREVIEW;
708                 else if (idtype == ID_TE) sce->r.scemode |= R_TEXNODE_PREVIEW;
709                 sce->r.mode &= ~R_OSA;
710         }
711         else {  /* PR_BUTS_RENDER */
712                 sce->r.mode |= R_OSA;
713         }
714
715
716         /* callbacs are cleared on GetRender() */
717         if (ELEM(sp->pr_method, PR_BUTS_RENDER, PR_NODE_RENDER)) {
718                 RE_display_draw_cb(re, sp, shader_preview_draw);
719         }
720         /* set this for all previews, default is react to G.is_break still */
721         RE_test_break_cb(re, sp, shader_preview_break);
722         
723         /* lens adjust */
724         oldlens = ((Camera *)sce->camera->data)->lens;
725         if (sizex > sp->sizey)
726                 ((Camera *)sce->camera->data)->lens *= (float)sp->sizey / (float)sizex;
727
728         /* entire cycle for render engine */
729         RE_PreviewRender(re, pr_main, sce);
730
731         ((Camera *)sce->camera->data)->lens = oldlens;
732
733         /* handle results */
734         if (sp->pr_method == PR_ICON_RENDER) {
735                 // char *rct= (char *)(sp->pr_rect + 32*16 + 16);
736                 
737                 if (sp->pr_rect)
738                         RE_ResultGet32(re, sp->pr_rect);
739         }
740         else {
741                 /* validate owner */
742                 //if (ri->rect == NULL)
743                 //      ri->rect= MEM_mallocN(sizeof(int) * ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
744                 //RE_ResultGet32(re, ri->rect);
745         }
746
747         /* unassign the pointers, reset vars */
748         preview_prepare_scene(sp->scene, NULL, GS(id->name), sp);
749         
750         /* XXX bad exception, end-exec is not being called in render, because it uses local main */
751 //      if (idtype == ID_TE) {
752 //              Tex *tex= (Tex *)id;
753 //              if (tex->use_nodes && tex->nodetree)
754 //                      ntreeEndExecTree(tex->nodetree);
755 //      }
756
757 }
758
759 /* runs inside thread for material and icons */
760 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
761 {
762         ShaderPreview *sp = customdata;
763
764         sp->stop = stop;
765         sp->do_update = do_update;
766
767         if (sp->parent) {
768                 shader_preview_render(sp, sp->id, 1, 1);
769                 shader_preview_render(sp, sp->parent, 1, 0);
770         }
771         else
772                 shader_preview_render(sp, sp->id, 0, 0);
773
774         *do_update = TRUE;
775 }
776
777 static void shader_preview_free(void *customdata)
778 {
779         ShaderPreview *sp = customdata;
780         Main *pr_main = sp->pr_main;
781         
782         if (sp->matcopy) {
783                 struct IDProperty *properties;
784                 
785                 /* node previews */
786                 shader_preview_updatejob(sp);
787                 
788                 /* get rid of copied material */
789                 BLI_remlink(&pr_main->mat, sp->matcopy);
790                 
791                 BKE_material_free_ex(sp->matcopy, FALSE);
792
793                 properties = IDP_GetProperties((ID *)sp->matcopy, FALSE);
794                 if (properties) {
795                         IDP_FreeProperty(properties);
796                         MEM_freeN(properties);
797                 }
798                 MEM_freeN(sp->matcopy);
799         }
800         if (sp->texcopy) {
801                 struct IDProperty *properties;
802                 /* node previews */
803                 shader_preview_updatejob(sp);
804                 
805                 /* get rid of copied texture */
806                 BLI_remlink(&pr_main->tex, sp->texcopy);
807                 BKE_texture_free(sp->texcopy);
808                 
809                 properties = IDP_GetProperties((ID *)sp->texcopy, FALSE);
810                 if (properties) {
811                         IDP_FreeProperty(properties);
812                         MEM_freeN(properties);
813                 }
814                 MEM_freeN(sp->texcopy);
815         }
816         if (sp->worldcopy) {
817                 struct IDProperty *properties;
818                 /* node previews */
819                 shader_preview_updatejob(sp);
820                 
821                 /* get rid of copied world */
822                 BLI_remlink(&pr_main->world, sp->worldcopy);
823                 BKE_world_free_ex(sp->worldcopy, TRUE); /* [#32865] - we need to unlink the texture copies, unlike for materials */
824                 
825                 properties = IDP_GetProperties((ID *)sp->worldcopy, FALSE);
826                 if (properties) {
827                         IDP_FreeProperty(properties);
828                         MEM_freeN(properties);
829                 }
830                 MEM_freeN(sp->worldcopy);
831         }
832         if (sp->lampcopy) {
833                 struct IDProperty *properties;
834                 /* node previews */
835                 shader_preview_updatejob(sp);
836                 
837                 /* get rid of copied lamp */
838                 BLI_remlink(&pr_main->lamp, sp->lampcopy);
839                 BKE_lamp_free(sp->lampcopy);
840                 
841                 properties = IDP_GetProperties((ID *)sp->lampcopy, FALSE);
842                 if (properties) {
843                         IDP_FreeProperty(properties);
844                         MEM_freeN(properties);
845                 }
846                 MEM_freeN(sp->lampcopy);
847         }
848         
849         MEM_freeN(sp);
850 }
851
852 /* ************************* icon preview ********************** */
853
854 static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned int *rect)
855 {
856         struct ImBuf *ima;
857         unsigned int *drect, *srect;
858         float scaledx, scaledy;
859         short ex, ey, dx, dy;
860
861         /* paranoia test */
862         if (ibuf == NULL || (ibuf->rect == NULL && ibuf->rect_float == NULL))
863                 return;
864         
865         /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
866         ima = IMB_dupImBuf(ibuf);
867         
868         if (!ima) 
869                 return;
870         
871         if (ima->x > ima->y) {
872                 scaledx = (float)w;
873                 scaledy =  ( (float)ima->y / (float)ima->x) * (float)w;
874         }
875         else {
876                 scaledx =  ( (float)ima->x / (float)ima->y) * (float)h;
877                 scaledy = (float)h;
878         }
879         
880         ex = (short)scaledx;
881         ey = (short)scaledy;
882         
883         dx = (w - ex) / 2;
884         dy = (h - ey) / 2;
885         
886         IMB_scalefastImBuf(ima, ex, ey);
887         
888         /* if needed, convert to 32 bits */
889         if (ima->rect == NULL)
890                 IMB_rect_from_float(ima);
891
892         srect = ima->rect;
893         drect = rect;
894
895         drect += dy * w + dx;
896         for (; ey > 0; ey--) {
897                 memcpy(drect, srect, ex * sizeof(int));
898                 drect += w;
899                 srect += ima->x;
900         }
901
902         IMB_freeImBuf(ima);
903 }
904
905 static void set_alpha(char *cp, int sizex, int sizey, char alpha) 
906 {
907         int a, size = sizex * sizey;
908
909         for (a = 0; a < size; a++, cp += 4)
910                 cp[3] = alpha;
911 }
912
913 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
914 {
915         ShaderPreview *sp = customdata;
916         ID *id = sp->id;
917         short idtype = GS(id->name);
918         
919         if (idtype == ID_IM) {
920                 Image *ima = (Image *)id;
921                 ImBuf *ibuf = NULL;
922                 ImageUser iuser = {NULL};
923
924                 /* ima->ok is zero when Image cannot load */
925                 if (ima == NULL || ima->ok == 0)
926                         return;
927
928                 /* setup dummy image user */
929                 iuser.ok = iuser.framenr = 1;
930                 iuser.scene = sp->scene;
931                 
932                 /* elubie: this needs to be changed: here image is always loaded if not
933                  * already there. Very expensive for large images. Need to find a way to 
934                  * only get existing ibuf */
935                 ibuf = BKE_image_acquire_ibuf(ima, &iuser, NULL);
936                 if (ibuf == NULL || ibuf->rect == NULL) {
937                         BKE_image_release_ibuf(ima, ibuf, NULL);
938                         return;
939                 }
940                 
941                 icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
942
943                 *do_update = TRUE;
944
945                 BKE_image_release_ibuf(ima, ibuf, NULL);
946         }
947         else if (idtype == ID_BR) {
948                 Brush *br = (Brush *)id;
949
950                 br->icon_imbuf = get_brush_icon(br);
951
952                 memset(sp->pr_rect, 0x888888, sp->sizex * sp->sizey * sizeof(unsigned int));
953
954                 if (!(br->icon_imbuf) || !(br->icon_imbuf->rect))
955                         return;
956
957                 icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
958
959                 *do_update = TRUE;
960         }
961         else {
962                 /* re-use shader job */
963                 shader_preview_startjob(customdata, stop, do_update);
964
965                 /* world is rendered with alpha=0, so it wasn't displayed 
966                  * this could be render option for sky to, for later */
967                 if (idtype == ID_WO) {
968                         set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
969                 }
970                 else if (idtype == ID_MA) {
971                         Material *ma = (Material *)id;
972
973                         if (ma->material_type == MA_TYPE_HALO)
974                                 set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
975                 }
976         }
977 }
978
979 /* use same function for icon & shader, so the job manager
980  * does not run two of them at the same time. */
981
982 static void common_preview_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
983 {
984         ShaderPreview *sp = customdata;
985
986         if (sp->pr_method == PR_ICON_RENDER)
987                 icon_preview_startjob(customdata, stop, do_update);
988         else
989                 shader_preview_startjob(customdata, stop, do_update);
990 }
991
992 /* exported functions */
993
994 static void icon_preview_add_size(IconPreview *ip, unsigned int *rect, int sizex, int sizey)
995 {
996         IconPreviewSize *cur_size = ip->sizes.first, *new_size;
997
998         while (cur_size) {
999                 if (cur_size->sizex == sizex && cur_size->sizey == sizey) {
1000                         /* requested size is already in list, no need to add it again */
1001                         return;
1002                 }
1003
1004                 cur_size = cur_size->next;
1005         }
1006
1007         new_size = MEM_callocN(sizeof(IconPreviewSize), "IconPreviewSize");
1008         new_size->sizex = sizex;
1009         new_size->sizey = sizey;
1010         new_size->rect = rect;
1011
1012         BLI_addtail(&ip->sizes, new_size);
1013 }
1014
1015 static void icon_preview_startjob_all_sizes(void *customdata, short *stop, short *do_update, float *progress)
1016 {
1017         IconPreview *ip = (IconPreview *)customdata;
1018         IconPreviewSize *cur_size = ip->sizes.first;
1019
1020         while (cur_size) {
1021                 ShaderPreview *sp = MEM_callocN(sizeof(ShaderPreview), "Icon ShaderPreview");
1022
1023                 /* construct shader preview from image size and previewcustomdata */
1024                 sp->scene = ip->scene;
1025                 sp->owner = ip->owner;
1026                 sp->sizex = cur_size->sizex;
1027                 sp->sizey = cur_size->sizey;
1028                 sp->pr_method = PR_ICON_RENDER;
1029                 sp->pr_rect = cur_size->rect;
1030                 sp->id = ip->id;
1031                 sp->pr_main = pr_main;
1032
1033                 common_preview_startjob(sp, stop, do_update, progress);
1034                 shader_preview_free(sp);
1035
1036                 cur_size = cur_size->next;
1037         }
1038 }
1039
1040 static void icon_preview_endjob(void *customdata)
1041 {
1042         IconPreview *ip = customdata;
1043
1044         if (ip->id) {
1045
1046                 if (GS(ip->id->name) == ID_BR)
1047                         WM_main_add_notifier(NC_BRUSH | NA_EDITED, ip->id);
1048 #if 0           
1049                 if (GS(ip->id->name) == ID_MA) {
1050                         Material *ma = (Material *)ip->id;
1051                         PreviewImage *prv_img = ma->preview;
1052                         int i;
1053
1054                         /* signal to gpu texture */
1055                         for (i = 0; i < NUM_ICON_SIZES; ++i) {
1056                                 if (prv_img->gputexture[i]) {
1057                                         GPU_texture_free(prv_img->gputexture[i]);
1058                                         prv_img->gputexture[i] = NULL;
1059                                         WM_main_add_notifier(NC_MATERIAL|ND_SHADING_DRAW, ip->id);
1060                                 }
1061                         }
1062                 }
1063 #endif
1064         }
1065 }
1066
1067 static void icon_preview_free(void *customdata)
1068 {
1069         IconPreview *ip = (IconPreview *)customdata;
1070
1071         BLI_freelistN(&ip->sizes);
1072         MEM_freeN(ip);
1073 }
1074
1075 void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *rect, int sizex, int sizey)
1076 {
1077         wmJob *wm_job;
1078         IconPreview *ip, *old_ip;
1079         
1080         /* suspended start means it starts after 1 timer step, see WM_jobs_timer below */
1081         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Icon Preview",
1082                              WM_JOB_EXCL_RENDER | WM_JOB_SUSPEND, WM_JOB_TYPE_RENDER_PREVIEW);
1083
1084         ip = MEM_callocN(sizeof(IconPreview), "icon preview");
1085
1086         /* render all resolutions from suspended job too */
1087         old_ip = WM_jobs_customdata_get(wm_job);
1088         if (old_ip)
1089                 BLI_movelisttolist(&ip->sizes, &old_ip->sizes);
1090
1091         /* customdata for preview thread */
1092         ip->scene = CTX_data_scene(C);
1093         ip->owner = id;
1094         ip->id = id;
1095
1096         icon_preview_add_size(ip, rect, sizex, sizey);
1097
1098         /* setup job */
1099         WM_jobs_customdata_set(wm_job, ip, icon_preview_free);
1100         WM_jobs_timer(wm_job, 0.1, NC_MATERIAL, NC_MATERIAL);
1101         WM_jobs_callbacks(wm_job, icon_preview_startjob_all_sizes, NULL, NULL, icon_preview_endjob);
1102
1103         WM_jobs_start(CTX_wm_manager(C), wm_job);
1104 }
1105
1106 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey, int method)
1107 {
1108         Object *ob = CTX_data_active_object(C);
1109         wmJob *wm_job;
1110         ShaderPreview *sp;
1111         Scene *scene = CTX_data_scene(C);
1112
1113         /* node previews not supported for cycles */
1114         if (BKE_scene_use_new_shading_nodes(scene) && method == PR_NODE_RENDER)
1115                 return;
1116
1117         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Shader Preview",
1118                             WM_JOB_EXCL_RENDER, WM_JOB_TYPE_RENDER_PREVIEW);
1119         sp = MEM_callocN(sizeof(ShaderPreview), "shader preview");
1120
1121         /* customdata for preview thread */
1122         sp->scene = scene;
1123         sp->owner = owner;
1124         sp->sizex = sizex;
1125         sp->sizey = sizey;
1126         sp->pr_method = method;
1127         sp->id = id;
1128         sp->parent = parent;
1129         sp->slot = slot;
1130
1131         /* hardcoded preview .blend for cycles/internal, this should be solved
1132          * once with custom preview .blend path for external engines */
1133         if (BKE_scene_use_new_shading_nodes(scene))
1134                 sp->pr_main = pr_main_cycles;
1135         else
1136                 sp->pr_main = pr_main;
1137
1138         if (ob && ob->totcol) copy_v4_v4(sp->col, ob->col);
1139         else sp->col[0] = sp->col[1] = sp->col[2] = sp->col[3] = 1.0f;
1140         
1141         /* setup job */
1142         WM_jobs_customdata_set(wm_job, sp, shader_preview_free);
1143         WM_jobs_timer(wm_job, 0.1, NC_MATERIAL, NC_MATERIAL);
1144         WM_jobs_callbacks(wm_job, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
1145         
1146         WM_jobs_start(CTX_wm_manager(C), wm_job);
1147 }
1148
1149 void ED_preview_kill_jobs(const struct bContext *C)
1150 {
1151         wmWindowManager *wm = CTX_wm_manager(C);
1152         if (wm)
1153                 WM_jobs_kill(wm, NULL, common_preview_startjob);
1154 }
1155