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